* Added KMessage to libroot_build.

* libbe_build: Where possible we directly use the actual Haiku headers and
  sources, now. In the headers/build headers we just include the respective
  Haiku headers as needed. That still allows overrides where necessary. The
  intention is to make it easier to keep the build stuff in sync.
* Fixed a few printf() format and signed/unsigned comparison warnings.


git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@42179 a95241bf-73f2-0310-859d-f6bbb57e9c96
This commit is contained in:
Ingo Weinhold 2011-06-14 11:42:49 +00:00
parent 45ec6bf344
commit 4cc4f7bb18
100 changed files with 136 additions and 20869 deletions

View File

@ -883,6 +883,7 @@ if ! $(HOST_PLATFORM_BEOS_COMPATIBLE) {
[ FDirName $(HAIKU_TOP) headers build os opengl ]
[ FDirName $(HAIKU_TOP) headers build os storage ]
[ FDirName $(HAIKU_TOP) headers build os support ]
[ FDirName $(HAIKU_TOP) headers build private ]
;
HOST_BE_API_CCFLAGS = -include BeOSBuildCompatibility.h ;
HOST_BE_API_C++FLAGS = $(HOST_BE_API_CCFLAGS) ;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2009-2010, Haiku, Inc. All Rights Reserved.
* Copyright 2009-2011, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _CONFIG_BUILD_TYPES_H
@ -70,13 +70,42 @@ typedef __haiku_std_uint64 __haiku_uint64;
#endif
#define __HAIKU_PHYS_SADDR_MIN (-__HAIKU_SADDR_MAX-1)
/* printf()/scanf() format prefixes */
/* TODO: The following are only guesses! We should define them in the
build/host headers. */
#define __HAIKU_STD_PRI_PREFIX_32 ""
#ifdef __HAIKU_ARCH_64_BIT
# define __HAIKU_STD_PRI_PREFIX_64 "l"
#else
# define __HAIKU_STD_PRI_PREFIX_64 "ll"
#endif
#define __HAIKU_PRI_PREFIX_32 __HAIKU_STD_PRI_PREFIX_32
#define __HAIKU_PRI_PREFIX_64 __HAIKU_STD_PRI_PREFIX_64
#ifdef __HAIKU_ARCH_64_BIT
# define __HAIKU_PRI_PREFIX_ADDR __HAIKU_PRI_PREFIX_64
#else
# define __HAIKU_PRI_PREFIX_ADDR __HAIKU_PRI_PREFIX_32
#endif
#ifdef __HAIKU_ARCH_PHYSICAL_64_BIT
# define __HAIKU_PRI_PREFIX_PHYS_ADDR __HAIKU_PRI_PREFIX_64
#else
# define __HAIKU_PRI_PREFIX_PHYS_ADDR __HAIKU_PRI_PREFIX_32
#endif
/* a generic address type wide enough for virtual and physical addresses */
#if __HAIKU_ARCH_BITS >= __HAIKU_ARCH_PHYSICAL_BITS
typedef __haiku_addr_t __haiku_generic_addr_t;
# define __HAIKU_GENERIC_ADDR_MAX __HAIKU_ADDR_MAX
# define __HAIKU_PRI_PREFIX_GENERIC_ADDR __HAIKU_PRI_PREFIX_ADDR
#else
typedef __haiku_phys_addr_t __haiku_generic_addr_t;
# define __HAIKU_GENERIC_ADDR_MAX __HAIKU_PHYS_ADDR_MAX
# define __HAIKU_PRI_PREFIX_GENERIC_ADDR __HAIKU_PRI_PREFIX_PHYS_ADDR
#endif

View File

@ -1,170 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: AppDefs.h
// Author: Erik Jaesler (erik@cgsoftware.com)
// Description: Message codes and the global cursors.
//------------------------------------------------------------------------------
#ifndef _APP_DEFS_H
#define _APP_DEFS_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
// Global Cursors --------------------------------------------------------------
// Old-style cursors
extern const unsigned char B_HAND_CURSOR[];
extern const unsigned char B_I_BEAM_CURSOR[];
// New-style cursors
#ifdef __cplusplus
class BCursor;
extern const BCursor *B_CURSOR_SYSTEM_DEFAULT;
extern const BCursor *B_CURSOR_I_BEAM;
#endif
// System Message Codes --------------------------------------------------------
enum {
B_ABOUT_REQUESTED = '_ABR',
B_WINDOW_ACTIVATED = '_ACT',
B_APP_ACTIVATED = '_ACT', // Same as B_WINDOW_ACTIVATED
B_ARGV_RECEIVED = '_ARG',
B_QUIT_REQUESTED = '_QRQ',
B_CLOSE_REQUESTED = '_QRQ', // Obsolete; use B_QUIT_REQUESTED
B_CANCEL = '_CNC',
B_KEY_DOWN = '_KYD',
B_KEY_UP = '_KYU',
B_UNMAPPED_KEY_DOWN = '_UKD',
B_UNMAPPED_KEY_UP = '_UKU',
B_MODIFIERS_CHANGED = '_MCH',
B_MINIMIZE = '_WMN',
B_MOUSE_DOWN = '_MDN',
B_MOUSE_MOVED = '_MMV',
B_MOUSE_ENTER_EXIT = '_MEX',
B_MOUSE_UP = '_MUP',
B_MOUSE_WHEEL_CHANGED = '_MWC',
B_OPEN_IN_WORKSPACE = '_OWS',
B_PRINTER_CHANGED = '_PCH',
B_PULSE = '_PUL',
B_READY_TO_RUN = '_RTR',
B_REFS_RECEIVED = '_RRC',
B_RELEASE_OVERLAY_LOCK = '_ROV',
B_ACQUIRE_OVERLAY_LOCK = '_AOV',
B_SCREEN_CHANGED = '_SCH',
B_VALUE_CHANGED = '_VCH',
B_VIEW_MOVED = '_VMV',
B_VIEW_RESIZED = '_VRS',
B_WINDOW_MOVED = '_WMV',
B_WINDOW_RESIZED = '_WRS',
B_WORKSPACES_CHANGED = '_WCG',
B_WORKSPACE_ACTIVATED = '_WAC',
B_ZOOM = '_WZM',
_COLORS_UPDATED = '_CLU', // Currently internal-use only. Later, public as B_COLORS_UPDATED
_FONTS_UPDATED = '_FNU', // Currently internal-use only. Later, public as B_FONTS_UPDATED
_APP_MENU_ = '_AMN',
_BROWSER_MENUS_ = '_BRM',
_MENU_EVENT_ = '_MEV',
_PING_ = '_PBL',
_QUIT_ = '_QIT',
_VOLUME_MOUNTED_ = '_NVL',
_VOLUME_UNMOUNTED_ = '_VRM',
_MESSAGE_DROPPED_ = '_MDP',
_DISPOSE_DRAG_ = '_DPD',
_MENUS_DONE_ = '_MND',
_SHOW_DRAG_HANDLES_ = '_SDH',
_EVENTS_PENDING_ = '_EVP',
_UPDATE_ = '_UPD',
_UPDATE_IF_NEEDED_ = '_UPN',
_PRINTER_INFO_ = '_PIN',
_SETUP_PRINTER_ = '_SUP',
_SELECT_PRINTER_ = '_PSL'
// Media Kit reserves all reserved codes starting in '_TR'
};
// Other Commands --------------------------------------------------------------
enum {
B_SET_PROPERTY = 'PSET',
B_GET_PROPERTY = 'PGET',
B_CREATE_PROPERTY = 'PCRT',
B_DELETE_PROPERTY = 'PDEL',
B_COUNT_PROPERTIES = 'PCNT',
B_EXECUTE_PROPERTY = 'PEXE',
B_GET_SUPPORTED_SUITES = 'SUIT',
B_UNDO = 'UNDO',
B_REDO = 'REDO',
B_CUT = 'CCUT',
B_COPY = 'COPY',
B_PASTE = 'PSTE',
B_SELECT_ALL = 'SALL',
B_SAVE_REQUESTED = 'SAVE',
B_MESSAGE_NOT_UNDERSTOOD = 'MNOT',
B_NO_REPLY = 'NONE',
B_REPLY = 'RPLY',
B_SIMPLE_DATA = 'DATA',
B_MIME_DATA = 'MIME',
B_ARCHIVED_OBJECT = 'ARCV',
B_UPDATE_STATUS_BAR = 'SBUP',
B_RESET_STATUS_BAR = 'SBRS',
B_NODE_MONITOR = 'NDMN',
B_QUERY_UPDATE = 'QUPD',
B_ENDORSABLE = 'ENDO',
B_COPY_TARGET = 'DDCP',
B_MOVE_TARGET = 'DDMV',
B_TRASH_TARGET = 'DDRM',
B_LINK_TARGET = 'DDLN',
B_INPUT_DEVICES_CHANGED = 'IDCH',
B_INPUT_METHOD_EVENT = 'IMEV',
B_WINDOW_MOVE_TO = 'WDMT',
B_WINDOW_MOVE_BY = 'WDMB',
B_SILENT_RELAUNCH = 'AREL',
B_OBSERVER_NOTICE_CHANGE = 'NTCH',
B_CONTROL_INVOKED = 'CIVK',
B_CONTROL_MODIFIED = 'CMOD'
// Media Kit reserves all reserved codes starting in 'TRI'
};
//------------------------------------------------------------------------------
#endif // _APP_DEFS_H
/*
* $Log $
*
* $Id $
*
*/
#include <../os/app/AppDefs.h>

View File

@ -1,149 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Handler.cpp
// Author: Erik Jaesler (erik@cgsoftware.com)
// Description: BHandler defines the message-handling protocol.
// MessageReceived() is its lynchpin.
//------------------------------------------------------------------------------
#ifndef _HANDLER_H
#define _HANDLER_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
#include <Archivable.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class BLooper;
class BMessageFilter;
class BMessage;
class BMessenger;
class BList;
class _ObserverList;
#define B_OBSERVE_WHAT_CHANGE "be:observe_change_what"
#define B_OBSERVE_ORIGINAL_WHAT "be:observe_orig_what"
const uint32 B_OBSERVER_OBSERVE_ALL = 0xffffffff;
// BHandler class --------------------------------------------------------------
class BHandler : public BArchivable {
public:
BHandler(const char* name = NULL);
virtual ~BHandler();
// Archiving
BHandler(BMessage* data);
static BArchivable* Instantiate(BMessage* data);
virtual status_t Archive(BMessage* data, bool deep = true) const;
// BHandler guts.
virtual void MessageReceived(BMessage* message);
BLooper* Looper() const;
void SetName(const char* name);
const char* Name() const;
virtual void SetNextHandler(BHandler* handler);
BHandler* NextHandler() const;
// Message filtering
virtual void AddFilter(BMessageFilter* filter);
virtual bool RemoveFilter(BMessageFilter* filter);
virtual void SetFilterList(BList* filters);
BList* FilterList();
bool LockLooper();
status_t LockLooperWithTimeout(bigtime_t timeout);
void UnlockLooper();
// Scripting
virtual BHandler* ResolveSpecifier(BMessage* msg,
int32 index,
BMessage* specifier,
int32 form,
const char* property);
virtual status_t GetSupportedSuites(BMessage* data);
// Observer calls, inter-looper and inter-team
status_t StartWatching(BMessenger, uint32 what);
status_t StartWatchingAll(BMessenger);
status_t StopWatching(BMessenger, uint32 what);
status_t StopWatchingAll(BMessenger);
// Observer calls for observing targets in the same BLooper
status_t StartWatching(BHandler* , uint32 what);
status_t StartWatchingAll(BHandler* );
status_t StopWatching(BHandler* , uint32 what);
status_t StopWatchingAll(BHandler* );
// Reserved
virtual status_t Perform(perform_code d, void* arg);
// Notifier calls
virtual void SendNotices(uint32 what, const BMessage* = 0);
bool IsWatched() const;
//----- Private or reserved -----------------------------------------
private:
typedef BArchivable _inherited;
friend inline int32 _get_object_token_(const BHandler* );
friend class BLooper;
friend class BMessageFilter;
virtual void _ReservedHandler2();
virtual void _ReservedHandler3();
virtual void _ReservedHandler4();
void InitData(const char* name);
BHandler(const BHandler&);
BHandler& operator=(const BHandler&);
void SetLooper(BLooper* loop);
int32 fToken;
char* fName;
BLooper* fLooper;
BHandler* fNextHandler;
BList* fFilters;
_ObserverList* fObserverList;
uint32 _reserved[3];
};
//------------------------------------------------------------------------------
#endif // _HANDLER_H
/*
* $Log $
*
* $Id $
*
*/
#include <../os/app/Handler.h>

View File

@ -1,238 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Looper.h
// Author(s): Erik Jaesler (erik@cgsoftware.com)
// DarkWyrm (bpmagic@columbus.rr.com)
// Description: BLooper class spawns a thread that runs a message loop.
//------------------------------------------------------------------------------
#ifndef _LOOPER_H
#define _LOOPER_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
#include <Handler.h>
#include <List.h>
#include <OS.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class BMessage;
class BMessageQueue;
namespace BPrivate {
class BLooperList;
}
struct _loop_data_;
// Port (Message Queue) Capacity -----------------------------------------------
#define B_LOOPER_PORT_DEFAULT_CAPACITY 100
// BLooper class ---------------------------------------------------------------
class BLooper : public BHandler {
public:
BLooper(const char* name = NULL,
int32 priority = B_NORMAL_PRIORITY,
int32 port_capacity = B_LOOPER_PORT_DEFAULT_CAPACITY);
virtual ~BLooper();
// Archiving
BLooper(BMessage* data);
static BArchivable* Instantiate(BMessage* data);
virtual status_t Archive(BMessage* data, bool deep = true) const;
// Message transmission
status_t PostMessage(uint32 command);
status_t PostMessage(BMessage* message);
status_t PostMessage(uint32 command,
BHandler* handler,
BHandler* reply_to = NULL);
status_t PostMessage(BMessage* message,
BHandler* handler,
BHandler* reply_to = NULL);
virtual void DispatchMessage(BMessage* message, BHandler* handler);
virtual void MessageReceived(BMessage* msg);
BMessage* CurrentMessage() const;
BMessage* DetachCurrentMessage();
BMessageQueue* MessageQueue() const;
bool IsMessageWaiting() const;
// Message handlers
void AddHandler(BHandler* handler);
bool RemoveHandler(BHandler* handler);
int32 CountHandlers() const;
BHandler* HandlerAt(int32 index) const;
int32 IndexOf(BHandler* handler) const;
BHandler* PreferredHandler() const;
void SetPreferredHandler(BHandler* handler);
// Loop control
virtual thread_id Run();
virtual void Quit();
virtual bool QuitRequested();
bool Lock();
void Unlock();
bool IsLocked() const;
status_t LockWithTimeout(bigtime_t timeout);
thread_id Thread() const;
team_id Team() const;
static BLooper* LooperForThread(thread_id tid);
// Loop debugging
thread_id LockingThread() const;
int32 CountLocks() const;
int32 CountLockRequests() const;
sem_id Sem() const;
// Scripting
virtual BHandler* ResolveSpecifier(BMessage* msg,
int32 index,
BMessage* specifier,
int32 form,
const char* property);
virtual status_t GetSupportedSuites(BMessage* data);
// Message filters (also see BHandler).
virtual void AddCommonFilter(BMessageFilter* filter);
virtual bool RemoveCommonFilter(BMessageFilter* filter);
virtual void SetCommonFilterList(BList* filters);
BList* CommonFilterList() const;
// Private or reserved ---------------------------------------------------------
virtual status_t Perform(perform_code d, void* arg);
protected:
// called from overridden task_looper
BMessage* MessageFromPort(bigtime_t = B_INFINITE_TIMEOUT);
private:
typedef BHandler _inherited;
friend class BWindow;
friend class BApplication;
friend class BMessenger;
friend class BView;
friend class BHandler;
friend class BPrivate::BLooperList;
friend port_id _get_looper_port_(const BLooper* );
friend status_t _safe_get_server_token_(const BLooper* , int32* );
friend team_id _find_cur_team_id_();
virtual void _ReservedLooper1();
virtual void _ReservedLooper2();
virtual void _ReservedLooper3();
virtual void _ReservedLooper4();
virtual void _ReservedLooper5();
virtual void _ReservedLooper6();
BLooper(const BLooper&);
BLooper& operator=(const BLooper&);
BLooper(int32 priority, port_id port, const char* name);
status_t _PostMessage(BMessage* msg,
BHandler* handler,
BHandler* reply_to);
static status_t _Lock(BLooper* loop,
port_id port,
bigtime_t timeout);
static status_t _LockComplete(BLooper* loop,
int32 old,
thread_id this_tid,
sem_id sem,
bigtime_t timeout);
void InitData();
void InitData(const char* name, int32 prio, int32 capacity);
void AddMessage(BMessage* msg);
void _AddMessagePriv(BMessage* msg);
static status_t _task0_(void* arg);
void* ReadRawFromPort(int32* code,
bigtime_t tout = B_INFINITE_TIMEOUT);
BMessage* ReadMessageFromPort(bigtime_t tout = B_INFINITE_TIMEOUT);
virtual BMessage* ConvertToMessage(void* raw, int32 code);
virtual void task_looper();
void do_quit_requested(BMessage* msg);
bool AssertLocked() const;
BHandler* top_level_filter(BMessage* msg, BHandler* t);
BHandler* handler_only_filter(BMessage* msg, BHandler* t);
BHandler* apply_filters( BList* list,
BMessage* msg,
BHandler* target);
void check_lock();
BHandler* resolve_specifier(BHandler* target, BMessage* msg);
void UnlockFully();
static uint32 sLooperID;
static team_id sTeamID;
// DEPRECATED
static void AddLooper(BLooper* l);
static bool IsLooperValid(const BLooper* l);
static void RemoveLooper(BLooper* l);
static void GetLooperList(BList* list);
static BLooper* LooperForName(const char* name);
static BLooper* LooperForPort(port_id port);
uint32 fLooperID;
BMessageQueue* fQueue;
BMessage* fLastMessage;
port_id fMsgPort;
long fAtomicCount;
sem_id fLockSem;
long fOwnerCount;
thread_id fOwner;
thread_id fTaskID;
uint32 _unused1;
int32 fInitPriority;
BHandler* fPreferred;
BList fHandlers;
BList* fCommonFilters;
bool fTerminating;
bool fRunCalled;
thread_id fCachedPid;
size_t fCachedStack;
void* fMsgBuffer;
size_t fMsgBufferSize;
uint32 _reserved[6];
};
//------------------------------------------------------------------------------
#endif // _LOOPER_H
/*
* $Log $
*
* $Id $
*
*/
#include <../os/app/Looper.h>

View File

@ -1,65 +1 @@
//
// $Id: MessageQueue.h 1686 2002-10-26 18:59:16Z beveloper $
//
// This is the BMessageQueue interface for OpenBeOS. It has been created
// to be source and binary compatible with the BeOS version of
// BMessageQueue.
//
#ifndef _OPENBEOS_MESSAGEQUEUE_H
#define _OPENBEOS_MESSAGEQUEUE_H
#include <Locker.h>
#include <Message.h> /* For convenience */
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
class BMessageQueue {
public:
BMessageQueue();
virtual ~BMessageQueue();
void AddMessage(BMessage *message);
void RemoveMessage(BMessage *message);
int32 CountMessages(void) const;
bool IsEmpty(void) const;
BMessage *FindMessage(int32 index) const;
BMessage *FindMessage(uint32 what, int32 index=0) const;
bool Lock(void);
void Unlock(void);
bool IsLocked(void);
BMessage *NextMessage(void);
private:
// Reserved space in the vtable for future changes to BMessageQueue
virtual void _ReservedMessageQueue1(void);
virtual void _ReservedMessageQueue2(void);
virtual void _ReservedMessageQueue3(void);
BMessageQueue(const BMessageQueue &);
BMessageQueue &operator=(const BMessageQueue &);
BMessage *fTheQueue;
BMessage *fQueueTail;
int32 fMessageCount;
BLocker fLocker;
// Reserved space for future changes to BMessageQueue
uint32 fReservedSpace[3];
};
#ifdef USE_OPENBEOS_NAMESPACE
}
#endif
#endif // _OPENBEOS_MESSAGEQUEUE_H
#include <../os/app/MessageQueue.h>

View File

@ -0,0 +1,3 @@
#define dprintf haiku_dprintf
#include <../os/drivers/KernelExport.h>
#undef dprintf

View File

@ -1,337 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: GraphicsDefs.h
// Author: Frans van Nispen
// Description: BMessageFilter class creates objects that filter
// in-coming BMessages.
//------------------------------------------------------------------------------
#ifndef _GRAPHICS_DEFS_H
#define _GRAPHICS_DEFS_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
#include <SupportDefs.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
//------------------------------------------------------------------------------
typedef struct pattern {
uint8 data[8];
} pattern;
#ifdef __cplusplus
inline bool
operator==(const pattern& a, const pattern& b)
{
return (*(uint64*)a.data == *(uint64*)b.data);
}
#endif // __cplusplus
extern _IMPEXP_BE const pattern B_SOLID_HIGH;
extern _IMPEXP_BE const pattern B_MIXED_COLORS;
extern _IMPEXP_BE const pattern B_SOLID_LOW;
//------------------------------------------------------------------------------
typedef struct rgb_color {
uint8 red;
uint8 green;
uint8 blue;
uint8 alpha;
#if defined(__cplusplus)
// some convenient additions
inline bool
operator==(const rgb_color& other) const
{
return *(const uint32 *)this == *(const uint32 *)&other;
}
inline bool
operator!=(const rgb_color& other) const
{
return *(const uint32 *)this != *(const uint32 *)&other;
}
#endif
} rgb_color;
//------------------------------------------------------------------------------
extern _IMPEXP_BE const rgb_color B_TRANSPARENT_COLOR;
extern _IMPEXP_BE const uint8 B_TRANSPARENT_MAGIC_CMAP8;
extern _IMPEXP_BE const uint16 B_TRANSPARENT_MAGIC_RGBA15;
extern _IMPEXP_BE const uint16 B_TRANSPARENT_MAGIC_RGBA15_BIG;
extern _IMPEXP_BE const uint32 B_TRANSPARENT_MAGIC_RGBA32;
extern _IMPEXP_BE const uint32 B_TRANSPARENT_MAGIC_RGBA32_BIG;
extern _IMPEXP_BE const uint8 B_TRANSPARENT_8_BIT;
extern _IMPEXP_BE const rgb_color B_TRANSPARENT_32_BIT;
//------------------------------------------------------------------------------
typedef struct color_map {
int32 id;
rgb_color color_list[256];
uint8 inversion_map[256];
uint8 index_map[32768];
} color_map;
typedef struct overlay_rect_limits {
uint16 horizontal_alignment;
uint16 vertical_alignment;
uint16 width_alignment;
uint16 height_alignment;
uint16 min_width;
uint16 max_width;
uint16 min_height;
uint16 max_height;
uint32 reserved[8];
} overlay_rect_limits;
typedef struct overlay_restrictions {
overlay_rect_limits source;
overlay_rect_limits destination;
float min_width_scale;
float max_width_scale;
float min_height_scale;
float max_height_scale;
uint32 reserved[8];
} overlay_restrictions;
//------------------------------------------------------------------------------
struct screen_id { int32 id; };
extern _IMPEXP_BE const struct screen_id B_MAIN_SCREEN_ID;
//------------------------------------------------------------------------------
typedef enum
{
B_NO_COLOR_SPACE = 0x0000, //* byte in memory order, high bit first
// linear color space (little endian is the default)
B_RGB32 = 0x0008, //* B[7:0] G[7:0] R[7:0] -[7:0]
B_RGBA32 = 0x2008, // B[7:0] G[7:0] R[7:0] A[7:0]
B_RGB24 = 0x0003, // B[7:0] G[7:0] R[7:0]
B_RGB16 = 0x0005, // G[2:0],B[4:0] R[4:0],G[5:3]
B_RGB15 = 0x0010, // G[2:0],B[4:0] -[0],R[4:0],G[4:3]
B_RGBA15 = 0x2010, // G[2:0],B[4:0] A[0],R[4:0],G[4:3]
B_CMAP8 = 0x0004, // D[7:0]
B_GRAY8 = 0x0002, // Y[7:0]
B_GRAY1 = 0x0001, // Y0[0],Y1[0],Y2[0],Y3[0],Y4[0],Y5[0],Y6[0],Y7[0]
// big endian version, when the encoding is not endianess independant
B_RGB32_BIG = 0x1008, // -[7:0] R[7:0] G[7:0] B[7:0]
B_RGBA32_BIG = 0x3008, // A[7:0] R[7:0] G[7:0] B[7:0]
B_RGB24_BIG = 0x1003, // R[7:0] G[7:0] B[7:0]
B_RGB16_BIG = 0x1005, // R[4:0],G[5:3] G[2:0],B[4:0]
B_RGB15_BIG = 0x1010, // -[0],R[4:0],G[4:3] G[2:0],B[4:0]
B_RGBA15_BIG = 0x3010, // A[0],R[4:0],G[4:3] G[2:0],B[4:0]
// little-endian declarations, for completness
B_RGB32_LITTLE = B_RGB32,
B_RGBA32_LITTLE = B_RGBA32,
B_RGB24_LITTLE = B_RGB24,
B_RGB16_LITTLE = B_RGB16,
B_RGB15_LITTLE = B_RGB15,
B_RGBA15_LITTLE = B_RGBA15,
// non linear color space -- note that these are here for exchange purposes;
// a BBitmap or BView may not necessarily support all these color spaces.
// Loss/Saturation points are Y 16-235 (absoulte); Cb/Cr 16-240 (center 128)
B_YCbCr422 = 0x4000, // Y0[7:0] Cb0[7:0] Y1[7:0] Cr0[7:0] Y2[7:0]...
// Cb2[7:0] Y3[7:0] Cr2[7:0]
B_YCbCr411 = 0x4001, // Cb0[7:0] Y0[7:0] Cr0[7:0] Y1[7:0] Cb4[7:0]...
// Y2[7:0] Cr4[7:0] Y3[7:0] Y4[7:0] Y5[7:0]...
// Y6[7:0] Y7[7:0]
B_YCbCr444 = 0x4003, // Y0[7:0] Cb0[7:0] Cr0[7:0]
B_YCbCr420 = 0x4004, // Non-interlaced only, Cb0 Y0 Y1 Cb2 Y2 Y3
// on even scan lines, Cr0 Y0 Y1 Cr2 Y2 Y3
// on odd scan lines
// Extrema points are
// Y 0 - 207 (absolute)
// U -91 - 91 (offset 128)
// V -127 - 127 (offset 128)
// note that YUV byte order is different from YCbCr
// USE YCbCr, not YUV, when that's what you mean!
B_YUV422 = 0x4020, // U0[7:0] Y0[7:0] V0[7:0] Y1[7:0] ...
// U2[7:0] Y2[7:0] V2[7:0] Y3[7:0]
B_YUV411 = 0x4021, // U0[7:0] Y0[7:0] Y1[7:0] V0[7:0] Y2[7:0] Y3[7:0]
// U4[7:0] Y4[7:0] Y5[7:0] V4[7:0] Y6[7:0] Y7[7:0]
B_YUV444 = 0x4023, // U0[7:0] Y0[7:0] V0[7:0] U1[7:0] Y1[7:0] V1[7:0]
B_YUV420 = 0x4024, // Non-interlaced only, U0 Y0 Y1 U2 Y2 Y3
// on even scan lines, V0 Y0 Y1 V2 Y2 Y3
// on odd scan lines
B_YUV9 = 0x402C, // planar? 410?
B_YUV12 = 0x402D, // planar? 420?
B_UVL24 = 0x4030, // U0[7:0] V0[7:0] L0[7:0] ...
B_UVL32 = 0x4031, // U0[7:0] V0[7:0] L0[7:0] X0[7:0]...
B_UVLA32 = 0x6031, // U0[7:0] V0[7:0] L0[7:0] A0[7:0]...
B_LAB24 = 0x4032, // L0[7:0] a0[7:0] b0[7:0] ... (a is not alpha!)
B_LAB32 = 0x4033, // L0[7:0] a0[7:0] b0[7:0] X0[7:0] ... (b is not alpha!)
B_LABA32 = 0x6033, // L0[7:0] a0[7:0] b0[7:0] A0[7:0] ... (A is alpha)
// red is at hue = 0
B_HSI24 = 0x4040, // H[7:0] S[7:0] I[7:0]
B_HSI32 = 0x4041, // H[7:0] S[7:0] I[7:0] X[7:0]
B_HSIA32 = 0x6041, // H[7:0] S[7:0] I[7:0] A[7:0]
B_HSV24 = 0x4042, // H[7:0] S[7:0] V[7:0]
B_HSV32 = 0x4043, // H[7:0] S[7:0] V[7:0] X[7:0]
B_HSVA32 = 0x6043, // H[7:0] S[7:0] V[7:0] A[7:0]
B_HLS24 = 0x4044, // H[7:0] L[7:0] S[7:0]
B_HLS32 = 0x4045, // H[7:0] L[7:0] S[7:0] X[7:0]
B_HLSA32 = 0x6045, // H[7:0] L[7:0] S[7:0] A[7:0]
B_CMY24 = 0xC001, // C[7:0] M[7:0] Y[7:0] No gray removal done
B_CMY32 = 0xC002, // C[7:0] M[7:0] Y[7:0] X[7:0] No gray removal done
B_CMYA32 = 0xE002, // C[7:0] M[7:0] Y[7:0] A[7:0] No gray removal done
B_CMYK32 = 0xC003, // C[7:0] M[7:0] Y[7:0] K[7:0]
// compatibility declarations
B_MONOCHROME_1_BIT = B_GRAY1,
B_GRAYSCALE_8_BIT = B_GRAY8,
B_COLOR_8_BIT = B_CMAP8,
B_RGB_32_BIT = B_RGB32,
B_RGB_16_BIT = B_RGB15,
B_BIG_RGB_32_BIT = B_RGB32_BIG,
B_BIG_RGB_16_BIT = B_RGB15_BIG
} color_space;
// Find out whether a specific color space is supported by BBitmaps.
// Support_flags will be set to what kinds of support are available.
// If support_flags is set to 0, false will be returned.
enum {
B_VIEWS_SUPPORT_DRAW_BITMAP = 0x1,
B_BITMAPS_SUPPORT_ATTACHED_VIEWS = 0x2
};
_IMPEXP_BE bool bitmaps_support_space(color_space space, uint32 * support_flags);
//------------------------------------------------------------------------------
// "pixel_chunk" is the native increment from one pixel starting on an integral byte
// to the next. "row_alignment" is the native alignment for pixel scanline starts.
// "pixels_per_chunk" is the number of pixels in a pixel_chunk. For instance, B_GRAY1
// sets pixel_chunk to 1, row_alignment to 4 and pixels_per_chunk to 8, whereas
// B_RGB24 sets pixel_chunk to 3, row_alignment to 4 and pixels_per_chunk to 1.
//------------------------------------------------------------------------------
_IMPEXP_BE status_t get_pixel_size_for(color_space space, size_t * pixel_chunk,
size_t * row_alignment, size_t * pixels_per_chunk);
enum buffer_orientation {
B_BUFFER_TOP_TO_BOTTOM,
B_BUFFER_BOTTOM_TO_TOP
};
enum buffer_layout {
B_BUFFER_NONINTERLEAVED = 1
};
//------------------------------------------------------------------------------
enum drawing_mode {
B_OP_COPY,
B_OP_OVER,
B_OP_ERASE,
B_OP_INVERT,
B_OP_ADD,
B_OP_SUBTRACT,
B_OP_BLEND,
B_OP_MIN,
B_OP_MAX,
B_OP_SELECT,
B_OP_ALPHA
};
enum source_alpha {
B_PIXEL_ALPHA=0,
B_CONSTANT_ALPHA
};
enum alpha_function {
B_ALPHA_OVERLAY=0,
B_ALPHA_COMPOSITE
};
enum {
B_8_BIT_640x480 = 0x00000001,
B_8_BIT_800x600 = 0x00000002,
B_8_BIT_1024x768 = 0x00000004,
B_8_BIT_1280x1024 = 0x00000008,
B_8_BIT_1600x1200 = 0x00000010,
B_16_BIT_640x480 = 0x00000020,
B_16_BIT_800x600 = 0x00000040,
B_16_BIT_1024x768 = 0x00000080,
B_16_BIT_1280x1024 = 0x00000100,
B_16_BIT_1600x1200 = 0x00000200,
B_32_BIT_640x480 = 0x00000400,
B_32_BIT_800x600 = 0x00000800,
B_32_BIT_1024x768 = 0x00001000,
B_32_BIT_1280x1024 = 0x00002000,
B_32_BIT_1600x1200 = 0x00004000,
B_8_BIT_1152x900 = 0x00008000,
B_16_BIT_1152x900 = 0x00010000,
B_32_BIT_1152x900 = 0x00020000,
B_15_BIT_640x480 = 0x00040000,
B_15_BIT_800x600 = 0x00080000,
B_15_BIT_1024x768 = 0x00100000,
B_15_BIT_1280x1024 = 0x00200000,
B_15_BIT_1600x1200 = 0x00400000,
B_15_BIT_1152x900 = 0x00800000,
// do not use B_FAKE_DEVICE--it will go away!
B_FAKE_DEVICE = 0x40000000,
B_8_BIT_640x400 = (int)0x80000000
};
#endif // _GRAPHICSDEFS_H
/*
* $Log $
*
* $Id $
*
*/
#include <../os/interface/GraphicsDefs.h>

View File

@ -1,392 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: InterfaceDefs.h
// Author: Erik Jaesler (erik@cgsoftware.com)
// Description: General Interface Kit definitions and global functions.
//------------------------------------------------------------------------------
#ifndef _INTERFACE_DEFS_H
#define _INTERFACE_DEFS_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
#include <GraphicsDefs.h>
#include <OS.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class BRect;
/*----------------------------------------------------------------*/
struct key_info {
uint32 modifiers;
uint8 key_states[16];
};
/*----------------------------------------------------------------*/
#define B_UTF8_ELLIPSIS "\xE2\x80\xA6"
#define B_UTF8_OPEN_QUOTE "\xE2\x80\x9C"
#define B_UTF8_CLOSE_QUOTE "\xE2\x80\x9D"
#define B_UTF8_COPYRIGHT "\xC2\xA9"
#define B_UTF8_REGISTERED "\xC2\xAE"
#define B_UTF8_TRADEMARK "\xE2\x84\xA2"
#define B_UTF8_SMILING_FACE "\xE2\x98\xBB"
#define B_UTF8_HIROSHI "\xE5\xBC\x98"
#ifdef COMPILE_FOR_R5
#define B_MAX_MOUSE_BUTTONS 3
#else
#define B_MAX_MOUSE_BUTTONS 16
#endif
/*----------------------------------------------------------------*/
enum { B_BACKSPACE = 0x08,
B_RETURN = 0x0a,
B_ENTER = 0x0a,
B_SPACE = 0x20,
B_TAB = 0x09,
B_ESCAPE = 0x1b,
B_SUBSTITUTE = 0x1a,
B_LEFT_ARROW = 0x1c,
B_RIGHT_ARROW = 0x1d,
B_UP_ARROW = 0x1e,
B_DOWN_ARROW = 0x1f,
B_INSERT = 0x05,
B_DELETE = 0x7f,
B_HOME = 0x01,
B_END = 0x04,
B_PAGE_UP = 0x0b,
B_PAGE_DOWN = 0x0c,
B_FUNCTION_KEY = 0x10 };
enum { B_F1_KEY = 0x02,
B_F2_KEY = 0x03,
B_F3_KEY = 0x04,
B_F4_KEY = 0x05,
B_F5_KEY = 0x06,
B_F6_KEY = 0x07,
B_F7_KEY = 0x08,
B_F8_KEY = 0x09,
B_F9_KEY = 0x0a,
B_F10_KEY = 0x0b,
B_F11_KEY = 0x0c,
B_F12_KEY = 0x0d,
B_PRINT_KEY = 0x0e,
B_SCROLL_KEY = 0x0f,
B_PAUSE_KEY = 0x10 };
struct key_map {
uint32 version;
uint32 caps_key;
uint32 scroll_key;
uint32 num_key;
uint32 left_shift_key;
uint32 right_shift_key;
uint32 left_command_key;
uint32 right_command_key;
uint32 left_control_key;
uint32 right_control_key;
uint32 left_option_key;
uint32 right_option_key;
uint32 menu_key;
uint32 lock_settings;
int32 control_map[128];
int32 option_caps_shift_map[128];
int32 option_caps_map[128];
int32 option_shift_map[128];
int32 option_map[128];
int32 caps_shift_map[128];
int32 caps_map[128];
int32 shift_map[128];
int32 normal_map[128];
int32 acute_dead_key[32];
int32 grave_dead_key[32];
int32 circumflex_dead_key[32];
int32 dieresis_dead_key[32];
int32 tilde_dead_key[32];
uint32 acute_tables;
uint32 grave_tables;
uint32 circumflex_tables;
uint32 dieresis_tables;
uint32 tilde_tables;
};
struct mouse_map {
uint32 button[B_MAX_MOUSE_BUTTONS];
};
/*----------------------------------------------------------------*/
enum border_style {
B_PLAIN_BORDER,
B_FANCY_BORDER,
B_NO_BORDER
};
/*----------------------------------------------------------------*/
enum orientation {
B_HORIZONTAL,
B_VERTICAL
};
/*----------------------------------------------------------------*/
enum button_width {
B_WIDTH_AS_USUAL,
B_WIDTH_FROM_WIDEST,
B_WIDTH_FROM_LABEL
};
/*----------------------------------------------------------------*/
enum join_mode {
B_ROUND_JOIN=0,
B_MITER_JOIN,
B_BEVEL_JOIN,
B_BUTT_JOIN,
B_SQUARE_JOIN
};
enum cap_mode {
B_ROUND_CAP=B_ROUND_JOIN,
B_BUTT_CAP=B_BUTT_JOIN,
B_SQUARE_CAP=B_SQUARE_JOIN
};
const float B_DEFAULT_MITER_LIMIT = 10.0F;
/*----------------------------------------------------------------*/
struct scroll_bar_info {
bool proportional;
bool double_arrows;
int32 knob;
int32 min_knob_size;
};
/*----------------------------------------------------------------*/
enum alignment {
B_ALIGN_LEFT,
B_ALIGN_RIGHT,
B_ALIGN_CENTER
};
enum vertical_alignment {
B_ALIGN_TOP = 0x10L,
B_ALIGN_MIDDLE = 0x20,
B_ALIGN_BOTTOM = 0x30,
B_ALIGN_NO_VERTICAL = -1L
};
/*----------------------------------------------------------------*/
enum {
B_CONTROL_TABLE = 0x00000001,
B_OPTION_CAPS_SHIFT_TABLE = 0x00000002,
B_OPTION_CAPS_TABLE = 0x00000004,
B_OPTION_SHIFT_TABLE = 0x00000008,
B_OPTION_TABLE = 0x00000010,
B_CAPS_SHIFT_TABLE = 0x00000020,
B_CAPS_TABLE = 0x00000040,
B_SHIFT_TABLE = 0x00000080,
B_NORMAL_TABLE = 0x00000100
};
/*----------------------------------------------------------------*/
enum {
B_SHIFT_KEY = 0x00000001,
B_COMMAND_KEY = 0x00000002,
B_CONTROL_KEY = 0x00000004,
B_CAPS_LOCK = 0x00000008,
B_SCROLL_LOCK = 0x00000010,
B_NUM_LOCK = 0x00000020,
B_OPTION_KEY = 0x00000040,
B_MENU_KEY = 0x00000080,
B_LEFT_SHIFT_KEY = 0x00000100,
B_RIGHT_SHIFT_KEY = 0x00000200,
B_LEFT_COMMAND_KEY = 0x00000400,
B_RIGHT_COMMAND_KEY = 0x00000800,
B_LEFT_CONTROL_KEY = 0x00001000,
B_RIGHT_CONTROL_KEY = 0x00002000,
B_LEFT_OPTION_KEY = 0x00004000,
B_RIGHT_OPTION_KEY = 0x00008000
};
/*----------------------------------------------------------------*/
enum bitmap_tiling {
B_TILE_BITMAP_X = 0x00000001,
B_TILE_BITMAP_Y = 0x00000002,
B_TILE_BITMAP = 0x00000003
};
enum overlay_options {
B_OVERLAY_FILTER_HORIZONTAL = 0x00010000,
B_OVERLAY_FILTER_VERTICAL = 0x00020000,
B_OVERLAY_MIRROR = 0x00040000,
B_OVERLAY_TRANSFER_CHANNEL = 0x00080000
};
/*----------------------------------------------------------------*/
_IMPEXP_BE status_t get_deskbar_frame(BRect *frame);
_IMPEXP_BE const color_map *system_colors();
_IMPEXP_BE status_t set_screen_space(int32 index, uint32 res,
bool stick = true);
_IMPEXP_BE status_t get_scroll_bar_info(scroll_bar_info *info);
_IMPEXP_BE status_t set_scroll_bar_info(scroll_bar_info *info);
_IMPEXP_BE status_t get_mouse_type(int32 *type);
_IMPEXP_BE status_t set_mouse_type(int32 type);
_IMPEXP_BE status_t get_mouse_map(mouse_map *map);
_IMPEXP_BE status_t set_mouse_map(mouse_map *map);
_IMPEXP_BE status_t get_click_speed(bigtime_t *speed);
_IMPEXP_BE status_t set_click_speed(bigtime_t speed);
_IMPEXP_BE status_t get_mouse_speed(int32 *speed);
_IMPEXP_BE status_t set_mouse_speed(int32 speed);
_IMPEXP_BE status_t get_mouse_acceleration(int32 *speed);
_IMPEXP_BE status_t set_mouse_acceleration(int32 speed);
_IMPEXP_BE status_t get_key_repeat_rate(int32 *rate);
_IMPEXP_BE status_t set_key_repeat_rate(int32 rate);
_IMPEXP_BE status_t get_key_repeat_delay(bigtime_t *delay);
_IMPEXP_BE status_t set_key_repeat_delay(bigtime_t delay);
_IMPEXP_BE uint32 modifiers();
_IMPEXP_BE status_t get_key_info(key_info *info);
_IMPEXP_BE void get_key_map(key_map **map, char **key_buffer);
_IMPEXP_BE status_t get_keyboard_id(uint16 *id);
_IMPEXP_BE void set_modifier_key(uint32 modifier, uint32 key);
_IMPEXP_BE void set_keyboard_locks(uint32 modifiers);
_IMPEXP_BE rgb_color keyboard_navigation_color();
_IMPEXP_BE int32 count_workspaces();
_IMPEXP_BE void set_workspace_count(int32 count);
_IMPEXP_BE int32 current_workspace();
_IMPEXP_BE void activate_workspace(int32 workspace);
_IMPEXP_BE bigtime_t idle_time();
_IMPEXP_BE void run_select_printer_panel();
_IMPEXP_BE void run_add_printer_panel();
_IMPEXP_BE void run_be_about();
_IMPEXP_BE void set_focus_follows_mouse(bool follow);
_IMPEXP_BE bool focus_follows_mouse();
enum mode_mouse {
B_NORMAL_MOUSE = 0,
B_FOCUS_FOLLOWS_MOUSE = 1,
B_WARP_MOUSE = 3,
B_INSTANT_WARP_MOUSE = 7
};
_IMPEXP_BE void set_mouse_mode(mode_mouse mode);
_IMPEXP_BE mode_mouse mouse_mode();
enum color_which {
B_PANEL_BACKGROUND_COLOR = 1,
B_PANEL_TEXT_COLOR = 10,
B_DOCUMENT_BACKGROUND_COLOR = 11,
B_DOCUMENT_TEXT_COLOR = 12,
B_CONTROL_BACKGROUND_COLOR = 13,
B_CONTROL_TEXT_COLOR = 14,
B_CONTROL_BORDER_COLOR = 15,
B_CONTROL_HIGHLIGHT_COLOR = 16,
B_NAVIGATION_BASE_COLOR = 4,
B_NAVIGATION_PULSE_COLOR = 17,
B_SHINE_COLOR = 18,
B_SHADOW_COLOR = 19,
B_MENU_BACKGROUND_COLOR = 2,
B_MENU_SELECTED_BACKGROUND_COLOR = 6,
B_MENU_ITEM_TEXT_COLOR = 7,
B_MENU_SELECTED_ITEM_TEXT_COLOR = 8,
B_MENU_SELECTED_BORDER_COLOR = 9,
B_TOOLTIP_BACKGROUND_COLOR = 20,
B_TOOLTIP_TEXT_COLOR = 21,
B_SUCCESS_COLOR = 100,
B_FAILURE_COLOR = 101,
// Old name synonyms.
B_KEYBOARD_NAVIGATION_COLOR = B_NAVIGATION_BASE_COLOR,
B_MENU_SELECTION_BACKGROUND_COLOR = B_MENU_SELECTED_BACKGROUND_COLOR,
// These are deprecated -- do not use in new code. See BScreen for
// the replacement for B_DESKTOP_COLOR.
B_DESKTOP_COLOR = 5,
B_WINDOW_TAB_COLOR = 3,
B_RANDOM_COLOR = 0x80000000,
B_MICHELANGELO_FAVORITE_COLOR,
B_DSANDLER_FAVORITE_SKY_COLOR,
B_DSANDLER_FAVORITE_INK_COLOR,
B_DSANDLER_FAVORITE_SHOES_COLOR
};
_IMPEXP_BE rgb_color ui_color(color_which which);
_IMPEXP_BE rgb_color tint_color(rgb_color color, float tint);
extern "C" status_t _init_interface_kit_();
/* effects on standard gray level */
const float B_LIGHTEN_MAX_TINT = 0.0F; /* 216 --> 255.0 (255) */
const float B_LIGHTEN_2_TINT = 0.385F; /* 216 --> 240.0 (240) */
const float B_LIGHTEN_1_TINT = 0.590F; /* 216 --> 232.0 (232) */
const float B_NO_TINT = 1.0F; /* 216 --> 216.0 (216) */
const float B_DARKEN_1_TINT = 1.147F; /* 216 --> 184.2 (184) */
const float B_DARKEN_2_TINT = 1.295F; /* 216 --> 152.3 (152) */
const float B_DARKEN_3_TINT = 1.407F; /* 216 --> 128.1 (128) */
const float B_DARKEN_4_TINT = 1.555F; /* 216 --> 96.1 (96) */
const float B_DARKEN_MAX_TINT = 2.0F; /* 216 --> 0.0 (0) */
const float B_DISABLED_LABEL_TINT = B_DARKEN_3_TINT;
const float B_HIGHLIGHT_BACKGROUND_TINT = B_DARKEN_2_TINT;
const float B_DISABLED_MARK_TINT = B_LIGHTEN_2_TINT;
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
#endif // _INTERFACE_DEFS_H
#include <../os/interface/InterfaceDefs.h>

View File

@ -1,114 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Point.h
// Author: Frans van Nispen
// Description: BPoint represents a single x,y coordinate.
//------------------------------------------------------------------------------
#ifndef _POINT_H
#define _POINT_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <BeBuild.h>
#include <SupportDefs.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class BRect;
// BPoint class ----------------------------------------------------------------
class BPoint {
public:
float x;
float y;
BPoint();
BPoint(float X, float Y);
BPoint(const BPoint &p);
BPoint &operator=(const BPoint &p);
void Set(float X, float Y);
void ConstrainTo(BRect r);
void PrintToStream() const;
BPoint operator+(const BPoint &p) const;
BPoint operator-(const BPoint &p) const;
BPoint& operator+=(const BPoint &p);
BPoint& operator-=(const BPoint &p);
bool operator!=(const BPoint &p) const;
bool operator==(const BPoint &p) const;
};
//------------------------------------------------------------------------------
extern _IMPEXP_BE const BPoint B_ORIGIN; // returns (0,0)
//------------------------------------------------------------------------------
inline BPoint::BPoint()
{
x = y = 0;
}
//------------------------------------------------------------------------------
inline BPoint::BPoint(float X, float Y)
{
x = X;
y = Y;
}
//------------------------------------------------------------------------------
inline BPoint::BPoint(const BPoint& pt)
{
x = pt.x;
y = pt.y;
}
//------------------------------------------------------------------------------
inline BPoint &BPoint::operator=(const BPoint& from)
{
x = from.x;
y = from.y;
return *this;
}
//------------------------------------------------------------------------------
inline void BPoint::Set(float X, float Y)
{
x = X;
y = Y;
}
//------------------------------------------------------------------------------
#endif // _POINT_H
/*
* $Log $
*
* $Id $
*
*/
#include <../os/interface/Point.h>

View File

@ -1,213 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2005, Haiku
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Rect.h
// Author: Frans van Nispen (xlr8@tref.nl)
// Description: BRect represents a rectangular area.
//------------------------------------------------------------------------------
#ifndef _RECT_H
#define _RECT_H
#include <SupportDefs.h>
#include <Point.h>
#include <math.h>
class BRect {
public:
float left;
float top;
float right;
float bottom;
BRect();
BRect(const BRect &r);
BRect(float l, float t, float r, float b);
BRect(BPoint lt, BPoint rb);
BRect &operator=(const BRect &r);
void Set(float l, float t, float r, float b);
void PrintToStream() const;
BPoint LeftTop() const;
BPoint RightBottom() const;
BPoint LeftBottom() const;
BPoint RightTop() const;
void SetLeftTop(const BPoint p);
void SetRightBottom(const BPoint p);
void SetLeftBottom(const BPoint p);
void SetRightTop(const BPoint p);
// transformation
void InsetBy(BPoint p);
void InsetBy(float dx, float dy);
void OffsetBy(BPoint p);
void OffsetBy(float dx, float dy);
void OffsetTo(BPoint p);
void OffsetTo(float x, float y);
// expression transformations
BRect& InsetBySelf(BPoint);
BRect& InsetBySelf(float dx, float dy);
BRect InsetByCopy(BPoint);
BRect InsetByCopy(float dx, float dy);
BRect& OffsetBySelf(BPoint);
BRect& OffsetBySelf(float dx, float dy);
BRect OffsetByCopy(BPoint);
BRect OffsetByCopy(float dx, float dy);
BRect& OffsetToSelf(BPoint);
BRect& OffsetToSelf(float dx, float dy);
BRect OffsetToCopy(BPoint);
BRect OffsetToCopy(float dx, float dy);
// comparison
bool operator==(BRect r) const;
bool operator!=(BRect r) const;
// intersection and union
BRect operator&(BRect r) const;
BRect operator|(BRect r) const;
bool Intersects(BRect r) const;
bool IsValid() const;
float Width() const;
int32 IntegerWidth() const;
float Height() const;
int32 IntegerHeight() const;
bool Contains(BPoint p) const;
bool Contains(BRect r) const;
};
// inline definitions ----------------------------------------------------------
inline BPoint
BRect::LeftTop() const
{
return *(const BPoint *)&left;
}
inline BPoint
BRect::RightBottom() const
{
return *(const BPoint *)&right;
}
inline BPoint
BRect::LeftBottom() const
{
return BPoint(left, bottom);
}
inline BPoint
BRect::RightTop() const
{
return BPoint(right, top);
}
inline
BRect::BRect()
{
top = left = 0;
bottom = right = -1;
}
inline
BRect::BRect(float l, float t, float r, float b)
{
left = l;
top = t;
right = r;
bottom = b;
}
inline
BRect::BRect(const BRect &r)
{
left = r.left;
top = r.top;
right = r.right;
bottom = r.bottom;
}
inline
BRect::BRect(BPoint leftTop, BPoint rightBottom)
{
left = leftTop.x;
top = leftTop.y;
right = rightBottom.x;
bottom = rightBottom.y;
}
inline BRect &
BRect::operator=(const BRect& from)
{
left = from.left;
top = from.top;
right = from.right;
bottom = from.bottom;
return *this;
}
inline void
BRect::Set(float l, float t, float r, float b)
{
left = l;
top = t;
right = r;
bottom = b;
}
inline bool
BRect::IsValid() const
{
return left <= right && top <= bottom;
}
inline int32
BRect::IntegerWidth() const
{
return (int32)ceil(right - left);
}
inline float
BRect::Width() const
{
return right - left;
}
inline int32
BRect::IntegerHeight() const
{
return (int32)ceil(bottom - top);
}
inline float
BRect::Height() const
{
return bottom - top;
}
#endif // _RECT_H
#include <../os/interface/Rect.h>

View File

@ -1,95 +1 @@
/*
* Copyright 2007, Haiku. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _REGION_H
#define _REGION_H
#include <BeBuild.h>
#include <Rect.h>
namespace BPrivate {
class ServerLink;
class LinkReceiver;
};
/* Integer rect used to define a clipping rectangle. All bounds are inclusive. */
/* Moved from DirectWindow.h */
typedef struct {
int32 left;
int32 top;
int32 right;
int32 bottom;
} clipping_rect;
class BRegion {
public:
BRegion();
BRegion(const BRegion& region);
BRegion(const BRect rect);
virtual ~BRegion();
BRegion &operator=(const BRegion &from);
void Set(BRect newBounds);
void Set(clipping_rect newBounds);
BRect Frame() const;
clipping_rect FrameInt() const;
BRect RectAt(int32 index) /*const*/;
clipping_rect RectAtInt(int32 index) /*const*/;
int32 CountRects() /*const*/;
bool Intersects(BRect rect) const;
bool Intersects(clipping_rect rect) const;
bool Contains(BPoint point) const;
bool Contains(int32 x, int32 y) /*const*/;
void PrintToStream() const;
void OffsetBy(int32 x, int32 y);
void MakeEmpty();
void Include(BRect rect);
void Include(clipping_rect rect);
void Include(const BRegion*);
void Exclude(BRect r);
void Exclude(clipping_rect r);
void Exclude(const BRegion* region);
void IntersectWith(const BRegion* region);
private:
friend class BDirectWindow;
friend class BPrivate::ServerLink;
friend class BPrivate::LinkReceiver;
class Support;
friend class Support;
private:
BRegion(const clipping_rect& rect);
void _AdoptRegionData(BRegion& region);
bool _SetSize(long newSize);
clipping_rect _Convert(const BRect& rect) const;
clipping_rect _ConvertToInternal(const BRect& rect) const;
clipping_rect _ConvertToInternal(
const clipping_rect& rect) const;
private:
long fCount;
long fDataSize;
clipping_rect fBounds;
clipping_rect* fData;
};
#endif // _REGION_H
#include <../os/interface/Region.h>

View File

@ -0,0 +1 @@
#include <../os/interface/Size.h>

View File

@ -1,627 +1 @@
/* Kernel specific structures and functions
*
* Copyright 2004, Haiku Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _OS_H
#define _OS_H
#include <stdarg.h>
#include <SupportDefs.h>
#include <StorageDefs.h>
#ifdef __cplusplus
extern "C" {
#endif
/*-------------------------------------------------------------*/
/* System constants */
#define B_OS_NAME_LENGTH 32
#define B_PAGE_SIZE 4096
#define B_INFINITE_TIMEOUT (9223372036854775807LL)
enum {
B_TIMEOUT = 8, /* relative timeout */
B_RELATIVE_TIMEOUT = 8, /* fails after a relative timeout with B_WOULD_BLOCK */
B_ABSOLUTE_TIMEOUT = 16, /* fails after an absolute timeout with B_WOULD BLOCK */
};
/*-------------------------------------------------------------*/
/* Types */
typedef int32 area_id;
typedef int32 port_id;
typedef int32 sem_id;
typedef int32 team_id;
typedef int32 thread_id;
/*-------------------------------------------------------------*/
/* Areas */
typedef struct area_info {
area_id area;
char name[B_OS_NAME_LENGTH];
size_t size;
uint32 lock;
uint32 protection;
team_id team;
uint32 ram_size;
uint32 copy_count;
uint32 in_count;
uint32 out_count;
void *address;
} area_info;
/* area locking */
#define B_NO_LOCK 0
#define B_LAZY_LOCK 1
#define B_FULL_LOCK 2
#define B_CONTIGUOUS 3
#define B_LOMEM 4
/* address spec for create_area(), and clone_area() */
#define B_ANY_ADDRESS 0
#define B_EXACT_ADDRESS 1
#define B_BASE_ADDRESS 2
#define B_CLONE_ADDRESS 3
#define B_ANY_KERNEL_ADDRESS 4
/* area protection */
#define B_READ_AREA 1
#define B_WRITE_AREA 2
extern area_id create_area(const char *name, void **start_addr, uint32 addr_spec,
size_t size, uint32 lock, uint32 protection);
extern area_id clone_area(const char *name, void **dest_addr, uint32 addr_spec,
uint32 protection, area_id source);
extern area_id find_area(const char *name);
extern area_id area_for(void *address);
extern status_t delete_area(area_id id);
extern status_t resize_area(area_id id, size_t new_size);
extern status_t set_area_protection(area_id id, uint32 new_protection);
/* system private, use macros instead */
extern status_t _get_area_info(area_id id, area_info *areaInfo, size_t size);
extern status_t _get_next_area_info(team_id team, int32 *cookie, area_info *areaInfo, size_t size);
#define get_area_info(id, ainfo) \
_get_area_info((id), (ainfo),sizeof(*(ainfo)))
#define get_next_area_info(team, cookie, ainfo) \
_get_next_area_info((team), (cookie), (ainfo), sizeof(*(ainfo)))
/*-------------------------------------------------------------*/
/* Ports */
typedef struct port_info {
port_id port;
team_id team;
char name[B_OS_NAME_LENGTH];
int32 capacity; /* queue depth */
int32 queue_count; /* # msgs waiting to be read */
int32 total_count; /* total # msgs read so far */
} port_info;
extern port_id create_port(int32 capacity, const char *name);
extern port_id find_port(const char *name);
extern ssize_t read_port(port_id port, int32 *code, void *buffer, size_t bufferSize);
extern ssize_t read_port_etc(port_id port, int32 *code, void *buffer, size_t bufferSize,
uint32 flags, bigtime_t timeout);
extern status_t write_port(port_id port, int32 code, const void *buffer, size_t bufferSize);
extern status_t write_port_etc(port_id port, int32 code, const void *buffer, size_t bufferSize,
uint32 flags, bigtime_t timeout);
extern status_t close_port(port_id port);
extern status_t delete_port(port_id port);
extern ssize_t port_buffer_size(port_id port);
extern ssize_t port_buffer_size_etc(port_id port, uint32 flags, bigtime_t timeout);
extern ssize_t port_count(port_id port);
extern status_t set_port_owner(port_id port, team_id team);
/* system private, use the macros instead */
extern status_t _get_port_info(port_id port, port_info *portInfo, size_t portInfoSize);
extern status_t _get_next_port_info(team_id team, int32 *cookie, port_info *portInfo,
size_t portInfoSize);
#define get_port_info(port, info) \
_get_port_info((port), (info), sizeof(*(info)))
#define get_next_port_info(team, cookie, info) \
_get_next_port_info((team), (cookie), (info), sizeof(*(info)))
/*-------------------------------------------------------------*/
/* Semaphores */
typedef struct sem_info {
sem_id sem;
team_id team;
char name[B_OS_NAME_LENGTH];
int32 count;
thread_id latest_holder;
} sem_info;
/* semaphore flags */
enum {
B_CAN_INTERRUPT = 0x01, // acquisition of the semaphore can be
// interrupted (system use only)
B_CHECK_PERMISSION = 0x04, // ownership will be checked (system use
// only)
B_KILL_CAN_INTERRUPT = 0x20, // acquisition of the semaphore can be
// interrupted by SIGKILL[THR], even
// if not B_CAN_INTERRUPT (system use
// only)
/* release_sem_etc() only flags */
B_DO_NOT_RESCHEDULE = 0x02, // thread is not rescheduled
B_RELEASE_ALL = 0x08, // all waiting threads will be woken up,
// count will be zeroed
B_RELEASE_IF_WAITING_ONLY = 0x10, // release count only if there are any
// threads waiting
};
extern sem_id create_sem(int32 count, const char *name);
extern status_t delete_sem(sem_id id);
extern status_t acquire_sem(sem_id id);
extern status_t acquire_sem_etc(sem_id id, int32 count, uint32 flags, bigtime_t timeout);
extern status_t release_sem(sem_id id);
extern status_t release_sem_etc(sem_id id, int32 count, uint32 flags);
// ToDo: the following two calls are not part of the BeOS API, and might be
// changed or even removed for the final release of Haiku R1
extern status_t switch_sem(sem_id semToBeReleased, sem_id id);
extern status_t switch_sem_etc(sem_id semToBeReleased, sem_id id, int32 count,
uint32 flags, bigtime_t timeout);
extern status_t get_sem_count(sem_id id, int32 *threadCount);
extern status_t set_sem_owner(sem_id id, team_id team);
/* system private, use the macros instead */
extern status_t _get_sem_info(sem_id id, struct sem_info *info, size_t infoSize);
extern status_t _get_next_sem_info(team_id team, int32 *cookie, struct sem_info *info,
size_t infoSize);
#define get_sem_info(sem, info) \
_get_sem_info((sem), (info), sizeof(*(info)))
#define get_next_sem_info(team, cookie, info) \
_get_next_sem_info((team), (cookie), (info), sizeof(*(info)))
/*-------------------------------------------------------------*/
/* Teams */
typedef struct {
team_id team;
int32 thread_count;
int32 image_count;
int32 area_count;
thread_id debugger_nub_thread;
port_id debugger_nub_port;
int32 argc;
char args[64];
uid_t uid;
gid_t gid;
} team_info;
#define B_CURRENT_TEAM 0
#define B_SYSTEM_TEAM 2
extern status_t kill_team(team_id team);
/* see also: send_signal() */
/* system private, use macros instead */
extern status_t _get_team_info(team_id id, team_info *info, size_t size);
extern status_t _get_next_team_info(int32 *cookie, team_info *info, size_t size);
#define get_team_info(id, info) \
_get_team_info((id), (info), sizeof(*(info)))
#define get_next_team_info(cookie, info) \
_get_next_team_info((cookie), (info), sizeof(*(info)))
/* team usage info */
typedef struct {
bigtime_t user_time;
bigtime_t kernel_time;
} team_usage_info;
enum {
/* compatible to sys/resource.h RUSAGE_SELF and RUSAGE_CHILDREN */
B_TEAM_USAGE_SELF = 0,
B_TEAM_USAGE_CHILDREN = -1,
};
/* system private, use macros instead */
extern status_t _get_team_usage_info(team_id team, int32 who, team_usage_info *info, size_t size);
#define get_team_usage_info(team, who, info) \
_get_team_usage_info((team), (who), (info), sizeof(*(info)))
/*-------------------------------------------------------------*/
/* Threads */
typedef enum {
B_THREAD_RUNNING = 1,
B_THREAD_READY,
B_THREAD_RECEIVING,
B_THREAD_ASLEEP,
B_THREAD_SUSPENDED,
B_THREAD_WAITING
} thread_state;
typedef struct {
thread_id thread;
team_id team;
char name[B_OS_NAME_LENGTH];
thread_state state;
int32 priority;
sem_id sem;
bigtime_t user_time;
bigtime_t kernel_time;
void *stack_base;
void *stack_end;
} thread_info;
#define B_IDLE_PRIORITY 0
#define B_LOWEST_ACTIVE_PRIORITY 1
#define B_LOW_PRIORITY 5
#define B_NORMAL_PRIORITY 10
#define B_DISPLAY_PRIORITY 15
#define B_URGENT_DISPLAY_PRIORITY 20
#define B_REAL_TIME_DISPLAY_PRIORITY 100
#define B_URGENT_PRIORITY 110
#define B_REAL_TIME_PRIORITY 120
#define B_FIRST_REAL_TIME_PRIORITY B_REAL_TIME_DISPLAY_PRIORITY
#define B_MIN_PRIORITY B_IDLE_PRIORITY
#define B_MAX_PRIORITY B_REAL_TIME_PRIORITY
#define B_SYSTEM_TIMEBASE 0
typedef int32 (*thread_func) (void *);
#define thread_entry thread_func /* thread_entry is for backward compatibility only! Use thread_func */
extern thread_id spawn_thread(thread_func, const char *name, int32 priority, void *data);
extern status_t kill_thread(thread_id thread);
extern status_t resume_thread(thread_id thread);
extern status_t suspend_thread(thread_id thread);
extern status_t rename_thread(thread_id thread, const char *newName);
extern status_t set_thread_priority (thread_id thread, int32 newPriority);
extern void exit_thread(status_t status);
extern status_t wait_for_thread (thread_id thread, status_t *threadReturnValue);
extern status_t on_exit_thread(void (*callback)(void *), void *data);
extern thread_id find_thread(const char *name);
extern status_t send_data(thread_id thread, int32 code, const void *buffer,
size_t bufferSize);
extern int32 receive_data(thread_id *sender, void *buffer, size_t bufferSize);
extern bool has_data(thread_id thread);
extern status_t snooze(bigtime_t amount);
extern status_t snooze_etc(bigtime_t amount, int timeBase, uint32 flags);
extern status_t snooze_until(bigtime_t time, int timeBase);
/* system private, use macros instead */
extern status_t _get_thread_info(thread_id id, thread_info *info, size_t size);
extern status_t _get_next_thread_info(team_id team, int32 *cookie,
thread_info *info, size_t size);
#define get_thread_info(id, info) \
_get_thread_info((id), (info), sizeof(*(info)))
#define get_next_thread_info(team, cookie, info) \
_get_next_thread_info((team), (cookie), (info), sizeof(*(info)))
/*-------------------------------------------------------------*/
/* Time */
extern uint32 real_time_clock(void);
extern void set_real_time_clock(uint32 secs_since_jan1_1970);
extern bigtime_t real_time_clock_usecs(void);
extern status_t set_timezone(char *timezone);
extern bigtime_t system_time(void); /* time since booting in microseconds */
/*-------------------------------------------------------------*/
/* Alarm */
enum {
B_ONE_SHOT_ABSOLUTE_ALARM = 1,
B_ONE_SHOT_RELATIVE_ALARM,
B_PERIODIC_ALARM /* "when" specifies the period */
};
extern bigtime_t set_alarm(bigtime_t when, uint32 flags);
/*-------------------------------------------------------------*/
/* Debugger */
extern void debugger(const char *message);
/*
calling this function with a non-zero value will cause your thread
to receive signals for any exceptional conditions that occur (i.e.
you'll get SIGSEGV for data access exceptions, SIGFPE for floating
point errors, SIGILL for illegal instructions, etc).
to re-enable the default debugger pass a zero.
*/
extern int disable_debugger(int state);
// TODO: Remove. Temporary debug helper.
extern void debug_printf(const char *format, ...)
__attribute__ ((format (__printf__, 1, 2)));
extern void debug_vprintf(const char *format, va_list args);
/*-------------------------------------------------------------*/
/* System information */
#if __INTEL__
# define B_MAX_CPU_COUNT 8
#elif __POWERPC__
# define B_MAX_CPU_COUNT 8
#endif
#define OBOS_CPU_TYPES
typedef enum cpu_types {
// ToDo: add latest models
/* Motorola/IBM */
B_CPU_PPC_601 = 1,
B_CPU_PPC_603 = 2,
B_CPU_PPC_603e = 3,
B_CPU_PPC_604 = 4,
B_CPU_PPC_604e = 5,
B_CPU_PPC_750 = 6,
B_CPU_PPC_686 = 13,
/* Intel */
/* Updated according to Intel(R) Processor Identification and
* the CPUID instruction (Table 4)
* AP-485 Intel - 24161828.pdf
*/
B_CPU_INTEL_x86 = 0x1000,
B_CPU_INTEL_PENTIUM = 0x1051,
B_CPU_INTEL_PENTIUM75,
B_CPU_INTEL_PENTIUM_486_OVERDRIVE,
B_CPU_INTEL_PENTIUM_MMX,
B_CPU_INTEL_PENTIUM_MMX_MODEL_4 = B_CPU_INTEL_PENTIUM_MMX,
B_CPU_INTEL_PENTIUM_MMX_MODEL_8 = 0x1058,
B_CPU_INTEL_PENTIUM75_486_OVERDRIVE,
B_CPU_INTEL_PENTIUM_PRO = 0x1061,
B_CPU_INTEL_PENTIUM_II = 0x1063,
B_CPU_INTEL_PENTIUM_II_MODEL_3 = 0x1063,
B_CPU_INTEL_PENTIUM_II_MODEL_5 = 0x1065,
B_CPU_INTEL_CELERON = 0x1066,
B_CPU_INTEL_PENTIUM_III = 0x1067,
B_CPU_INTEL_PENTIUM_III_MODEL_8 = 0x1068,
B_CPU_INTEL_PENTIUM_M = 0x1069,
B_CPU_INTEL_PENTIUM_III_XEON = 0x106a,
B_CPU_INTEL_PENTIUM_III_MODEL_11 = 0x106b,
B_CPU_INTEL_PENTIUM_M_MODEL_13 = 0x106d, /* Dothan */
B_CPU_INTEL_PENTIUM_IV = 0x10f0,
B_CPU_INTEL_PENTIUM_IV_MODEL_1,
B_CPU_INTEL_PENTIUM_IV_MODEL_2,
B_CPU_INTEL_PENTIUM_IV_MODEL_3,
B_CPU_INTEL_PENTIUM_IV_MODEL_4,
/* AMD */
/* Checked with "AMD Processor Recognition Application Note"
* (Table 3)
* 20734.pdf
*/
B_CPU_AMD_x86 = 0x1100,
B_CPU_AMD_K5_MODEL_0 = 0x1150,
B_CPU_AMD_K5_MODEL_1,
B_CPU_AMD_K5_MODEL_2,
B_CPU_AMD_K5_MODEL_3,
B_CPU_AMD_K6_MODEL_6 = 0x1156,
B_CPU_AMD_K6_MODEL_7 = 0x1157,
B_CPU_AMD_K6_MODEL_8 = 0x1158,
B_CPU_AMD_K6_2 = 0x1158,
B_CPU_AMD_K6_MODEL_9 = 0x1159,
B_CPU_AMD_K6_III = 0x1159,
B_CPU_AMD_K6_III_MODEL_13 = 0x115d,
B_CPU_AMD_ATHLON_MODEL_1 = 0x1161,
B_CPU_AMD_ATHLON_MODEL_2 = 0x1162,
B_CPU_AMD_DURON = 0x1163,
B_CPU_AMD_ATHLON_THUNDERBIRD = 0x1164,
B_CPU_AMD_ATHLON_XP = 0x1166,
B_CPU_AMD_ATHLON_XP_MODEL_7,
B_CPU_AMD_ATHLON_XP_MODEL_8,
B_CPU_AMD_ATHLON_XP_MODEL_10 = 0x116a, /* Barton */
B_CPU_AMD_SEMPRON_MODEL_8 = B_CPU_AMD_ATHLON_XP_MODEL_8,
B_CPU_AMD_SEMPRON_MODEL_10 = B_CPU_AMD_ATHLON_XP_MODEL_10,
/* According to "Revision guide for AMD Athlon 64
* and AMD Opteron Processors" (25759.pdf)
*/
B_CPU_AMD_ATHLON_64_MODEL_4 = 0x11f4,
B_CPU_AMD_ATHLON_64_MODEL_5,
B_CPU_AMD_OPTERON = B_CPU_AMD_ATHLON_64_MODEL_5,
B_CPU_AMD_ATHLON_64_FX = B_CPU_AMD_ATHLON_64_MODEL_5,
B_CPU_AMD_ATHLON_64_MODEL_7 = 0x11f7,
B_CPU_AMD_ATHLON_64_MODEL_8,
B_CPU_AMD_ATHLON_64_MODEL_11 = 0x11fb,
B_CPU_AMD_ATHLON_64_MODEL_12,
B_CPU_AMD_ATHLON_64_MODEL_14 = 0x11fe,
B_CPU_AMD_ATHLON_64_MODEL_15,
/* VIA/Cyrix */
B_CPU_CYRIX_x86 = 0x1200,
B_CPU_VIA_CYRIX_x86 = 0x1200,
B_CPU_CYRIX_GXm = 0x1254,
B_CPU_CYRIX_6x86MX = 0x1260,
/* VIA/IDT */
B_CPU_IDT_x86 = 0x1300,
B_CPU_VIA_IDT_x86 = 0x1300,
B_CPU_IDT_WINCHIP_C6 = 0x1354,
B_CPU_IDT_WINCHIP_2 = 0x1358,
B_CPU_IDT_WINCHIP_3,
B_CPU_VIA_EDEN = 0x1367,
B_CPU_VIA_EDEN_EZRA_T = 0x1368,
/* Transmeta */
B_CPU_TRANSMETA_x86 = 0x1600,
B_CPU_TRANSMETA_CRUSOE = 0x1654,
/* Rise */
B_CPU_RISE_x86 = 0x1400,
B_CPU_RISE_mP6 = 0x1450,
/* National Semiconductor */
B_CPU_NATIONAL_x86 = 0x1500,
B_CPU_NATIONAL_GEODE_GX1 = 0x1554,
B_CPU_NATIONAL_GEODE_GX2,
/* For compatibility */
B_CPU_AMD_29K = 14,
B_CPU_x86,
B_CPU_MC6502,
B_CPU_Z80,
B_CPU_ALPHA,
B_CPU_MIPS,
B_CPU_HPPA,
B_CPU_M68K,
B_CPU_ARM,
B_CPU_SH,
B_CPU_SPARC,
} cpu_type;
#define B_CPU_x86_VENDOR_MASK 0xff00
#ifdef __INTEL__
typedef union {
struct {
uint32 max_eax;
char vendor_id[12];
} eax_0;
struct {
uint32 stepping : 4;
uint32 model : 4;
uint32 family : 4;
uint32 type : 2;
uint32 reserved_0 : 2;
uint32 extended_model : 4;
uint32 extended_family : 8;
uint32 reserved_1 : 4;
uint32 reserved_2;
uint32 features;
uint32 reserved_3;
} eax_1;
struct {
uint8 call_num;
uint8 cache_descriptors[15];
} eax_2;
struct {
uint32 reserved[2];
uint32 serial_number_high;
uint32 serial_number_low;
} eax_3;
char as_chars[16];
struct {
uint32 eax;
uint32 ebx;
uint32 edx;
uint32 ecx;
} regs;
} cpuid_info;
extern status_t get_cpuid(cpuid_info *info, uint32 eaxRegister, uint32 cpuNum);
#endif
typedef enum platform_types {
B_BEBOX_PLATFORM = 0,
B_MAC_PLATFORM,
B_AT_CLONE_PLATFORM,
B_ENIAC_PLATFORM,
B_APPLE_II_PLATFORM,
B_CRAY_PLATFORM,
B_LISA_PLATFORM,
B_TI_994A_PLATFORM,
B_TIMEX_SINCLAIR_PLATFORM,
B_ORAC_1_PLATFORM,
B_HAL_PLATFORM,
B_BESM_6_PLATFORM,
B_MK_61_PLATFORM,
B_NINTENDO_64_PLATFORM
} platform_type;
typedef struct {
bigtime_t active_time; /* usec of doing useful work since boot */
} cpu_info;
typedef int32 machine_id[2]; /* unique machine ID */
typedef struct {
machine_id id; /* unique machine ID */
bigtime_t boot_time; /* time of boot (usecs since 1/1/1970) */
int32 cpu_count; /* number of cpus */
enum cpu_types cpu_type; /* type of cpu */
int32 cpu_revision; /* revision # of cpu */
cpu_info cpu_infos[B_MAX_CPU_COUNT]; /* info about individual cpus */
int64 cpu_clock_speed; /* processor clock speed (Hz) */
int64 bus_clock_speed; /* bus clock speed (Hz) */
enum platform_types platform_type; /* type of machine we're on */
int32 max_pages; /* total # physical pages */
int32 used_pages; /* # physical pages in use */
int32 page_faults; /* # of page faults */
int32 max_sems;
int32 used_sems;
int32 max_ports;
int32 used_ports;
int32 max_threads;
int32 used_threads;
int32 max_teams;
int32 used_teams;
char kernel_name[B_FILE_NAME_LENGTH]; /* name of kernel */
char kernel_build_date[B_OS_NAME_LENGTH]; /* date kernel built */
char kernel_build_time[B_OS_NAME_LENGTH]; /* time kernel built */
int64 kernel_version; /* version of this kernel */
bigtime_t _busy_wait_time; /* reserved for whatever */
int32 pad[4]; /* just in case... */
} system_info;
/* system private, use macro instead */
extern status_t _get_system_info(system_info *returned_info, size_t size);
#define get_system_info(info) \
_get_system_info((info), sizeof(*(info)))
extern int32 is_computer_on(void);
extern double is_computer_on_fire(void);
#ifdef __cplusplus
}
#endif
#endif /* _OS_H */
#include <../os/kernel/OS.h>

View File

@ -13,11 +13,7 @@
#include <Node.h>
#include <EntryList.h>
#include <StorageDefs.h>
#include <StorageDefs.Private.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
class BFile;
class BSymLink;
@ -107,10 +103,4 @@ private:
status_t create_directory(const char *path, mode_t mode);
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _DIRECTORY_H

View File

@ -1,156 +1 @@
/*
* Copyright 2003-2006, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _DISK_DEVICE_DEFS_H
#define _DISK_DEVICE_DEFS_H
#include <SupportDefs.h>
typedef int32 partition_id;
typedef int32 disk_system_id;
typedef int32 disk_job_id;
// partition flags
enum {
B_PARTITION_IS_DEVICE = 0x01,
B_PARTITION_FILE_SYSTEM = 0x02,
B_PARTITION_PARTITIONING_SYSTEM = 0x04,
B_PARTITION_READ_ONLY = 0x08,
B_PARTITION_MOUNTED = 0x10, // needed?
B_PARTITION_BUSY = 0x20,
B_PARTITION_DESCENDANT_BUSY = 0x40,
};
// partition statuses
enum {
B_PARTITION_VALID,
B_PARTITION_CORRUPT,
B_PARTITION_UNRECOGNIZED,
B_PARTITION_UNINITIALIZED, // Only when uninitialized manually.
// When not recognized while scanning it's
// B_PARTITION_UNRECOGNIZED.
};
// partition change flags
enum {
B_PARTITION_CHANGED_OFFSET = 0x000001,
B_PARTITION_CHANGED_SIZE = 0x000002,
B_PARTITION_CHANGED_CONTENT_SIZE = 0x000004,
B_PARTITION_CHANGED_BLOCK_SIZE = 0x000008,
B_PARTITION_CHANGED_STATUS = 0x000010,
B_PARTITION_CHANGED_FLAGS = 0x000020,
B_PARTITION_CHANGED_VOLUME = 0x000040,
B_PARTITION_CHANGED_NAME = 0x000080,
B_PARTITION_CHANGED_CONTENT_NAME = 0x000100,
B_PARTITION_CHANGED_TYPE = 0x000200,
B_PARTITION_CHANGED_CONTENT_TYPE = 0x000400,
B_PARTITION_CHANGED_PARAMETERS = 0x000800,
B_PARTITION_CHANGED_CONTENT_PARAMETERS = 0x001000,
B_PARTITION_CHANGED_CHILDREN = 0x002000,
B_PARTITION_CHANGED_DESCENDANTS = 0x004000,
B_PARTITION_CHANGED_DEFRAGMENTATION = 0x008000,
B_PARTITION_CHANGED_CHECK = 0x010000,
B_PARTITION_CHANGED_REPAIR = 0x020000,
B_PARTITION_CHANGED_INITIALIZATION = 0x040000,
};
// disk device flags
enum {
B_DISK_DEVICE_REMOVABLE = 0x01,
B_DISK_DEVICE_HAS_MEDIA = 0x02,
B_DISK_DEVICE_READ_ONLY = 0x04,
B_DISK_DEVICE_WRITE_ONCE = 0x08,
};
// disk system flags
enum {
B_DISK_SYSTEM_IS_FILE_SYSTEM = 0x0001,
// flags common for both file and partitioning systems
B_DISK_SYSTEM_SUPPORTS_CHECKING = 0x0002,
B_DISK_SYSTEM_SUPPORTS_REPAIRING = 0x0004,
B_DISK_SYSTEM_SUPPORTS_RESIZING = 0x0008,
B_DISK_SYSTEM_SUPPORTS_MOVING = 0x0010,
B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_NAME = 0x0020,
B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_PARAMETERS = 0x0040,
// file system specific flags
B_DISK_SYSTEM_SUPPORTS_DEFRAGMENTING = 0x0100,
B_DISK_SYSTEM_SUPPORTS_DEFRAGMENTING_WHILE_MOUNTED = 0x0200,
B_DISK_SYSTEM_SUPPORTS_CHECKING_WHILE_MOUNTED = 0x0400,
B_DISK_SYSTEM_SUPPORTS_REPAIRING_WHILE_MOUNTED = 0x0800,
B_DISK_SYSTEM_SUPPORTS_RESIZING_WHILE_MOUNTED = 0x1000,
B_DISK_SYSTEM_SUPPORTS_MOVING_WHILE_MOUNTED = 0x2000,
B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_NAME_WHILE_MOUNTED = 0x4000,
B_DISK_SYSTEM_SUPPORTS_SETTING_CONTENT_PARAMETERS_WHILE_MOUNTED = 0x8000,
// partitioning system specific flags
B_DISK_SYSTEM_SUPPORTS_RESIZING_CHILD = 0x0100,
B_DISK_SYSTEM_SUPPORTS_MOVING_CHILD = 0x0200,
B_DISK_SYSTEM_SUPPORTS_SETTING_NAME = 0x0400,
B_DISK_SYSTEM_SUPPORTS_SETTING_TYPE = 0x0800,
B_DISK_SYSTEM_SUPPORTS_SETTING_PARAMETERS = 0x1000,
B_DISK_SYSTEM_SUPPORTS_CREATING_CHILD = 0x2000,
B_DISK_SYSTEM_SUPPORTS_DELETING_CHILD = 0x4000,
B_DISK_SYSTEM_SUPPORTS_INITIALIZING = 0x8000,
};
// disk device job types
enum {
B_DISK_DEVICE_JOB_BAD_TYPE,
B_DISK_DEVICE_JOB_DEFRAGMENT,
B_DISK_DEVICE_JOB_REPAIR,
B_DISK_DEVICE_JOB_RESIZE,
B_DISK_DEVICE_JOB_MOVE,
B_DISK_DEVICE_JOB_SET_NAME,
B_DISK_DEVICE_JOB_SET_CONTENT_NAME,
B_DISK_DEVICE_JOB_SET_TYPE,
B_DISK_DEVICE_JOB_SET_PARMETERS,
B_DISK_DEVICE_JOB_SET_CONTENT_PARMETERS,
B_DISK_DEVICE_JOB_INITIALIZE,
B_DISK_DEVICE_JOB_UNINITIALIZE,
B_DISK_DEVICE_JOB_CREATE,
B_DISK_DEVICE_JOB_DELETE,
B_DISK_DEVICE_JOB_SCAN,
};
// disk device job statuses
enum {
B_DISK_DEVICE_JOB_UNINITIALIZED,
B_DISK_DEVICE_JOB_SCHEDULED,
B_DISK_DEVICE_JOB_IN_PROGRESS,
B_DISK_DEVICE_JOB_SUCCEEDED,
B_DISK_DEVICE_JOB_FAILED,
B_DISK_DEVICE_JOB_CANCELED,
};
// disk device job progress info
typedef struct disk_device_job_progress_info {
uint32 status;
uint32 interrupt_properties;
int32 task_count;
int32 completed_tasks;
float current_task_progress;
char current_task_description[256];
} disk_device_job_progress_info;
// disk device job interrupt properties
enum {
B_DISK_DEVICE_JOB_CAN_CANCEL = 0x01,
B_DISK_DEVICE_JOB_STOP_ON_CANCEL = 0x02,
B_DISK_DEVICE_JOB_REVERSE_ON_CANCEL = 0x04,
B_DISK_DEVICE_JOB_CAN_PAUSE = 0x08,
};
// string length constants, all of which include the NULL terminator
#define B_DISK_DEVICE_TYPE_LENGTH B_FILE_NAME_LENGTH
#define B_DISK_DEVICE_NAME_LENGTH B_FILE_NAME_LENGTH
#define B_DISK_SYSTEM_NAME_LENGTH B_PATH_NAME_LENGTH
// max size of parameter string buffers, including NULL terminator
#define B_DISK_DEVICE_MAX_PARAMETER_SIZE (32 * 1024)
#endif // _DISK_DEVICE_DEFS_H
#include <../os/storage/DiskDeviceDefs.h>

View File

@ -1,62 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file EntryList.h
BEntryList interface declaration.
*/
#ifndef _ENTRY_LIST_H
#define _ENTRY_LIST_H
#include <dirent.h>
#include <SupportDefs.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
// Forward declarations
class BEntry;
struct entry_ref;
//! Interface for iterating through a list of filesystem entries
/*! Defines a general interface for iterating through a list of entries (i.e.
files in a folder
@author <a href='mailto:tylerdauwalder@users.sf.net'>Tyler Dauwalder</a>
@author Be Inc.
@version 0.0.0
*/
class BEntryList {
public:
BEntryList();
virtual ~BEntryList();
virtual status_t GetNextEntry(BEntry *entry, bool traverse = false) = 0;
virtual status_t GetNextRef(entry_ref *ref) = 0;
virtual int32 GetNextDirents(struct dirent *buf, size_t length,
int32 count = INT_MAX) = 0;
virtual status_t Rewind() = 0;
virtual int32 CountEntries() = 0;
private:
virtual void _ReservedEntryList1();
virtual void _ReservedEntryList2();
virtual void _ReservedEntryList3();
virtual void _ReservedEntryList4();
virtual void _ReservedEntryList5();
virtual void _ReservedEntryList6();
virtual void _ReservedEntryList7();
virtual void _ReservedEntryList8();
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _ENTRY_LIST_H
#include <../os/storage/EntryList.h>

View File

@ -1,5 +1,5 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
@ -9,25 +9,22 @@
#ifndef _FILE_H
#define _FILE_H
#include <DataIO.h>
#include <Node.h>
#include <StorageDefs.Private.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
/*!
\class BFile
\brief BFile is a wrapper class for common operations on files providing
access to the file's content data and its attributes.
A BFile represents a file in some file system. It implements the
BPositionIO interface and thus the methods to read from and write to the
file, and is derived of BNode to provide access to the file's attributes.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class BFile : public BNode, public BPositionIO {
@ -57,6 +54,7 @@ public:
virtual off_t Position() const;
virtual status_t SetSize(off_t size);
virtual status_t GetSize(off_t* size) const;
BFile &operator=(const BFile &file);
@ -79,10 +77,5 @@ private:
uint32 fMode;
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _FILE_H

View File

@ -1,137 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file FindDirectory.h
Declarations of find_directory() functions and associated types.
*/
#ifndef _FIND_DIRECTORY_H
#define _FIND_DIRECTORY_H
#include <SupportDefs.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
/* ---
Per volume directories. When asking for these
directories, a volume must be specified, or the call will assume
the boot volume.
--- */
B_DESKTOP_DIRECTORY = 0,
B_TRASH_DIRECTORY,
/* ---
BeOS directories. These are mostly accessed read-only.
--- */
B_BEOS_DIRECTORY = 1000,
B_BEOS_SYSTEM_DIRECTORY,
B_BEOS_ADDONS_DIRECTORY,
B_BEOS_BOOT_DIRECTORY,
B_BEOS_FONTS_DIRECTORY,
B_BEOS_LIB_DIRECTORY,
B_BEOS_SERVERS_DIRECTORY,
B_BEOS_APPS_DIRECTORY,
B_BEOS_BIN_DIRECTORY,
B_BEOS_ETC_DIRECTORY,
B_BEOS_DOCUMENTATION_DIRECTORY,
B_BEOS_PREFERENCES_DIRECTORY,
B_BEOS_TRANSLATORS_DIRECTORY,
B_BEOS_MEDIA_NODES_DIRECTORY,
B_BEOS_SOUNDS_DIRECTORY,
/* ---
Common directories, shared among all users.
--- */
B_COMMON_DIRECTORY = 2000,
B_COMMON_SYSTEM_DIRECTORY,
B_COMMON_ADDONS_DIRECTORY,
B_COMMON_BOOT_DIRECTORY,
B_COMMON_FONTS_DIRECTORY,
B_COMMON_LIB_DIRECTORY,
B_COMMON_SERVERS_DIRECTORY,
B_COMMON_BIN_DIRECTORY,
B_COMMON_ETC_DIRECTORY,
B_COMMON_DOCUMENTATION_DIRECTORY,
B_COMMON_SETTINGS_DIRECTORY,
B_COMMON_DEVELOP_DIRECTORY,
B_COMMON_LOG_DIRECTORY,
B_COMMON_SPOOL_DIRECTORY,
B_COMMON_TEMP_DIRECTORY,
B_COMMON_VAR_DIRECTORY,
B_COMMON_TRANSLATORS_DIRECTORY,
B_COMMON_MEDIA_NODES_DIRECTORY,
B_COMMON_SOUNDS_DIRECTORY,
/* ---
User directories. These are interpreted in the context
of the user making the find_directory call.
--- */
B_USER_DIRECTORY = 3000,
B_USER_CONFIG_DIRECTORY,
B_USER_ADDONS_DIRECTORY,
B_USER_BOOT_DIRECTORY,
B_USER_FONTS_DIRECTORY,
B_USER_LIB_DIRECTORY,
B_USER_SETTINGS_DIRECTORY,
B_USER_DESKBAR_DIRECTORY,
B_USER_PRINTERS_DIRECTORY,
B_USER_TRANSLATORS_DIRECTORY,
B_USER_MEDIA_NODES_DIRECTORY,
B_USER_SOUNDS_DIRECTORY,
/* ---
Global directories.
--- */
B_APPS_DIRECTORY = 4000,
B_PREFERENCES_DIRECTORY,
B_UTILITIES_DIRECTORY
} directory_which;
/* ---
The C interface
--- */
status_t find_directory(directory_which which, dev_t volume, bool createIt,
char *pathString, int32 length);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
class BVolume;
class BPath;
/* ---
C++ interface
--- */
status_t find_directory(directory_which which, BPath *path,
bool createIt = false, BVolume *volume = NULL);
#endif
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _FIND_DIRECTORY_H
#include <../os/storage/FindDirectory.h>

View File

@ -1,93 +1 @@
#ifndef _NODE_MONITOR_H
#define _NODE_MONITOR_H
/* Node monitor calls for kernel add-ons
**
** Distributed under the terms of the OpenBeOS License.
*/
#include <StorageDefs.h>
/* Flags for the watch_node() call.
*
* Note that B_WATCH_MOUNT is NOT included in B_WATCH_ALL.
* You may prefer to use BVolumeRoster for volume watching.
*/
enum {
B_STOP_WATCHING = 0x0000,
B_WATCH_NAME = 0x0001,
B_WATCH_STAT = 0x0002,
B_WATCH_ATTR = 0x0004,
B_WATCH_DIRECTORY = 0x0008,
B_WATCH_ALL = 0x000f,
B_WATCH_MOUNT = 0x0010
};
/* The "opcode" field of the B_NODE_MONITOR notification message you get.
*
* The presence and meaning of the other fields in that message specifying what
* exactly caused the notification depend on this value.
*/
#define B_ENTRY_CREATED 1
#define B_ENTRY_REMOVED 2
#define B_ENTRY_MOVED 3
#define B_STAT_CHANGED 4
#define B_ATTR_CHANGED 5
#define B_DEVICE_MOUNTED 6
#define B_DEVICE_UNMOUNTED 7
// More specific info in the "cause" field of B_ATTR_CHANGED notification
// messages. (Haiku only)
#define B_ATTR_CREATED 1
#define B_ATTR_REMOVED 2
// B_ATTR_CHANGED is reused
// More specific info in the "fields" field of B_STAT_CHANGED notification
// messages, specifying what parts of the stat data have actually been
// changed. (Haiku only)
enum {
B_STAT_MODE = 0x01,
B_STAT_UID = 0x02,
B_STAT_GID = 0x04,
B_STAT_SIZE = 0x08,
B_STAT_ACCESS_TIME = 0x10,
B_STAT_MODIFICATION_TIME = 0x20,
B_STAT_CREATION_TIME = 0x40,
B_STAT_CHANGE_TIME = 0x80,
};
/* C++ callable Prototypes
*
* Since you are not able to parse BMessages from plain C, there is no
* API exported.
*/
#if defined(__cplusplus) && !defined(_KERNEL_MODE)
// these are only needed for the function exports
#include <Node.h>
#include <Messenger.h>
class BLooper;
class BHandler;
extern status_t watch_node(const node_ref *node, uint32 flags, BMessenger target);
extern status_t watch_node(const node_ref *node, uint32 flags,
const BHandler *handler,
const BLooper *looper = NULL);
extern status_t stop_watching(BMessenger target);
extern status_t stop_watching(const BHandler *handler, const BLooper *looper = NULL);
#endif /* __cplusplus && !_KERNEL_MODE */
#endif /* _NODE_MONITOR_H*/
#include <../os/storage/NodeMonitor.h>

View File

@ -1,103 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file Path.h
BPath interface declaration.
*/
#ifndef _PATH_H
#define _PATH_H
#include <Flattenable.h>
#include <StorageDefs.h>
#include <Message.h> /* for convenience, as in R5 */
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
// Forward declarations
class BDirectory;
class BEntry;
struct entry_ref;
/*!
\class BPath
\brief An absolute pathname wrapper class
Provides a convenient means of managing pathnames.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\author <a href="mailto:tylerdauwalder@users.sf.net">Tyler Dauwalder</a>
\version 0.0.0
*/
class BPath : public BFlattenable {
public:
BPath();
BPath(const BPath &path);
BPath(const entry_ref *ref);
BPath(const BEntry *entry);
BPath(const char *dir, const char *leaf = NULL, bool normalize = false);
BPath(const BDirectory *dir, const char *leaf, bool normalize = false);
virtual ~BPath();
status_t InitCheck() const;
status_t SetTo(const entry_ref *ref);
status_t SetTo(const BEntry *entry);
status_t SetTo(const char *path, const char *leaf = NULL,
bool normalize = false);
status_t SetTo(const BDirectory *dir, const char *path,
bool normalize = false);
void Unset();
status_t Append(const char *path, bool normalize = false);
const char *Path() const;
const char *Leaf() const;
status_t GetParent(BPath *path) const;
bool operator==(const BPath &item) const;
bool operator==(const char *path) const;
bool operator!=(const BPath &item) const;
bool operator!=(const char *path) const;
BPath& operator=(const BPath &item);
BPath& operator=(const char *path);
// BFlattenable protocol
virtual bool IsFixedSize() const;
virtual type_code TypeCode() const;
virtual ssize_t FlattenedSize() const;
virtual status_t Flatten(void *buffer, ssize_t size) const;
virtual bool AllowsTypeCode(type_code code) const;
virtual status_t Unflatten(type_code c, const void *buf, ssize_t size);
private:
virtual void _WarPath1();
virtual void _WarPath2();
virtual void _WarPath3();
uint32 _warData[4];
char *fName;
status_t fCStatus;
class EBadInput { };
status_t set_path(const char *path);
static bool MustNormalize(const char *path);
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _PATH_H
#include <../os/storage/Path.h>

View File

@ -1,92 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file ResourceStrings.h
BResourceStrings interface declaration.
*/
#ifndef _RESOURCE_STRINGS_H
#define _RESOURCE_STRINGS_H
#include <Entry.h>
#include <Locker.h>
class BResources;
class BString;
/*!
\class BResourceStrings
\brief Simple class to access the string resources in a file.
A BResourceStrings object reads the string type resources from a given
resource file and provides fast read only access to them.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class BResourceStrings {
public:
BResourceStrings();
BResourceStrings(const entry_ref &ref);
virtual ~BResourceStrings();
status_t InitCheck();
virtual BString *NewString(int32 id);
virtual const char *FindString(int32 id);
virtual status_t SetStringFile(const entry_ref *ref);
status_t GetStringFile(entry_ref *outRef);
public:
enum {
RESOURCE_TYPE = 'CSTR'
};
protected:
struct _string_id_hash {
_string_id_hash();
~_string_id_hash();
void assign_string(const char *str, bool makeCopy);
_string_id_hash *next;
int32 id;
char *data;
bool data_alloced;
bool _reserved1[3];
uint32 _reserved2;
};
protected:
BLocker _string_lock;
status_t _init_error;
private:
entry_ref fFileRef;
BResources *fResources;
_string_id_hash **fHashTable;
int32 fHashTableSize;
int32 fStringCount;
uint32 _reserved[16]; // FBC
private:
void _Cleanup();
void _MakeEmpty();
status_t _Rehash(int32 newSize);
_string_id_hash *_AddString(char *str, int32 id, bool wasMalloced);
virtual _string_id_hash *_FindString(int32 id);
// FBC
virtual status_t _Reserved_ResourceStrings_0(void *);
virtual status_t _Reserved_ResourceStrings_1(void *);
virtual status_t _Reserved_ResourceStrings_2(void *);
virtual status_t _Reserved_ResourceStrings_3(void *);
virtual status_t _Reserved_ResourceStrings_4(void *);
virtual status_t _Reserved_ResourceStrings_5(void *);
};
#endif // _RESOURCE_STRINGS_H
#include <../os/storage/ResourceStrings.h>

View File

@ -1,118 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file Resources.h
BResources interface declaration.
*/
#ifndef _RESOURCES_H
#define _RESOURCES_H
#include <File.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
namespace BPrivate {
namespace Storage {
class ResourcesContainer;
class ResourceFile;
};
};
/*!
\class BResources
\brief Represent the resources in a file
Provides an interface for accessing and manipulating resources.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class BResources {
public:
BResources();
BResources(const BFile *file, bool clobber = false);
virtual ~BResources();
status_t SetTo(const BFile *file, bool clobber = false);
void Unset();
status_t InitCheck() const;
const BFile &File() const;
const void *LoadResource(type_code type, int32 id, size_t *outSize);
const void *LoadResource(type_code type, const char *name,
size_t *outSize);
status_t PreloadResourceType(type_code type = 0);
status_t Sync();
status_t MergeFrom(BFile *fromFile);
status_t WriteTo(BFile *file);
status_t AddResource(type_code type, int32 id, const void *data,
size_t length, const char *name = NULL);
bool HasResource(type_code type, int32 id);
bool HasResource(type_code type, const char *name);
bool GetResourceInfo(int32 byIndex, type_code *typeFound, int32 *idFound,
const char **nameFound, size_t *lengthFound);
bool GetResourceInfo(type_code byType, int32 andIndex, int32 *idFound,
const char **nameFound, size_t *lengthFound);
bool GetResourceInfo(type_code byType, int32 andID,
const char **nameFound, size_t *lengthFound);
bool GetResourceInfo(type_code byType, const char *andName, int32 *idFound,
size_t *lengthFound);
bool GetResourceInfo(const void *byPointer, type_code *typeFound,
int32 *idFound, size_t *lengthFound,
const char **nameFound);
status_t RemoveResource(const void *resource);
status_t RemoveResource(type_code type, int32 id);
// deprecated
status_t WriteResource(type_code type, int32 id, const void *data,
off_t offset, size_t length);
status_t ReadResource(type_code type, int32 id, void *data, off_t offset,
size_t length);
void *FindResource(type_code type, int32 id, size_t *lengthFound);
void *FindResource(type_code type, const char *name, size_t *lengthFound);
private:
// FBC
virtual void _ReservedResources1();
virtual void _ReservedResources2();
virtual void _ReservedResources3();
virtual void _ReservedResources4();
virtual void _ReservedResources5();
virtual void _ReservedResources6();
virtual void _ReservedResources7();
virtual void _ReservedResources8();
private:
BFile fFile;
BPrivate::Storage::ResourcesContainer *fContainer;
BPrivate::Storage::ResourceFile *fResourceFile;
bool fReadOnly;
bool _pad[3];
uint32 _reserved[3]; // FBC
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _RESOURCES_H
#include <../os/storage/Resources.h>

View File

@ -1,21 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file StorageDefs.Private.h
Private Storage Kit declarations needed in public headers.
*/
#ifndef _DEF_STORAGE_PRIVATE_H
#define _DEF_STORAGE_PRIVATE_H
namespace BPrivate {
namespace Storage {
typedef int FileDescriptor;
};
};
#endif // _DEF_STORAGE_PRIVATE_H

View File

@ -1,58 +1,5 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file StorageDefs.h
Miscellaneous Storage Kit definitions and includes.
*/
#ifndef _DEF_STORAGE_H
#define _DEF_STORAGE_H
#include <fcntl.h>
#include <sys/param.h>
#include <limits.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif // USE_OPENBEOS_NAMESPACE
// Limits
#define B_DEV_NAME_LENGTH 128
#define B_FILE_NAME_LENGTH NAME_MAX
#define B_PATH_NAME_LENGTH MAXPATHLEN
#define B_ATTR_NAME_LENGTH (B_FILE_NAME_LENGTH-1)
#define B_MIME_TYPE_LENGTH (B_ATTR_NAME_LENGTH - 15)
#define B_MAX_SYMLINKS SYMLINK_MAX
// Open Modes
#define B_READ_ONLY O_RDONLY // read only
#define B_WRITE_ONLY O_WRONLY // write only
#define B_READ_WRITE O_RDWR // read and write
#define B_FAIL_IF_EXISTS O_EXCL // exclusive create
#define B_CREATE_FILE O_CREAT // create the file
#define B_ERASE_FILE O_TRUNC // erase the file's data
#define B_OPEN_AT_END O_APPEND // point to the end of the data
// Node Flavors
enum node_flavor {
B_FILE_NODE = 0x01,
B_SYMLINK_NODE = 0x02,
B_DIRECTORY_NODE = 0x04,
B_ANY_NODE = 0x07
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif // USE_OPENBEOS_NAMESPACE
#endif // _DEF_STORAGE_H
#include <../os/storage/StorageDefs.h>
#ifndef SYMLOOP_MAX
# define SYMLOOP_MAX 16
#endif

View File

@ -1,70 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//
// File Name: SymLink.h
//---------------------------------------------------------------------
/*!
\file SymLink.h
BSymLink interface declaration.
*/
#ifndef _SYM_LINK_H
#define _SYM_LINK_H
#include <Node.h>
#include <StorageDefs.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
class BPath;
/*!
\class BSymLink
\brief A symbolic link in the filesystem
Provides an interface for manipulating symbolic links.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class BSymLink : public BNode {
public:
BSymLink();
BSymLink(const BSymLink &link);
BSymLink(const entry_ref *ref);
BSymLink(const BEntry *entry);
BSymLink(const char *path);
BSymLink(const BDirectory *dir, const char *path);
virtual ~BSymLink();
ssize_t ReadLink(char *buf, size_t size);
ssize_t MakeLinkedPath(const char *dirPath, BPath *path);
ssize_t MakeLinkedPath(const BDirectory *dir, BPath *path);
bool IsAbsolute();
private:
virtual void _MissingSymLink1();
virtual void _MissingSymLink2();
virtual void _MissingSymLink3();
virtual void _MissingSymLink4();
virtual void _MissingSymLink5();
virtual void _MissingSymLink6();
uint32 _reservedData[4];
BEntry *fSecretEntry;
private:
int get_fd() const;
};
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif
#endif // _SYM_LINK_H
#include <../os/storage/SymLink.h>

View File

@ -1,73 +1 @@
/*
* Copyright (c) 2003 Marcus Overhagen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _BLOCK_CACHE_H
#define _BLOCK_CACHE_H
#include <BeBuild.h>
#include <Locker.h>
/* The OpenBeOS implementation of the BBlockCache.
* A class used to manage a pool of memory blocks.
*/
/* The allocation type to be used in the constructor
*/
enum {
B_OBJECT_CACHE = 0,
B_MALLOC_CACHE = 1
};
/* The BBlockCache class:
*/
class BBlockCache
{
public:
BBlockCache(uint32 blockCount,
size_t blockSize,
uint32 allocationType);
virtual ~BBlockCache();
void * Get(size_t blockSize);
void Save(void *pointer, size_t blockSize);
/* Private or reserved functions and data
*/
private:
virtual void _ReservedBlockCache1();
virtual void _ReservedBlockCache2();
BBlockCache(const BBlockCache &);
BBlockCache &operator=(const BBlockCache &);
struct _FreeBlock;
_FreeBlock *fFreeList;
size_t fBlockSize;
int32 fFreeBlocks;
int32 fBlockCount;
BLocker fLocker;
void * (*fAlloc)(size_t size);
void (*fFree)(void *pointer);
uint32 _reserved[2];
};
#endif
#include <../os/support/BlockCache.h>

View File

@ -1,132 +1 @@
/*
* Copyright 2007, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _BYTEORDER_H
#define _BYTEORDER_H
#include <BeBuild.h>
#include <endian.h>
#include <SupportDefs.h>
#include <TypeConstants.h>
/* for convenience */
/* swap directions */
typedef enum {
B_SWAP_HOST_TO_LENDIAN,
B_SWAP_HOST_TO_BENDIAN,
B_SWAP_LENDIAN_TO_HOST,
B_SWAP_BENDIAN_TO_HOST,
B_SWAP_ALWAYS
} swap_action;
/* BSD/networking macros */
#ifndef htonl
# define htonl(x) B_HOST_TO_BENDIAN_INT32(x)
# define ntohl(x) B_BENDIAN_TO_HOST_INT32(x)
# define htons(x) B_HOST_TO_BENDIAN_INT16(x)
# define ntohs(x) B_BENDIAN_TO_HOST_INT16(x)
#endif
/* always swap macros */
#define B_SWAP_DOUBLE(arg) __swap_double(arg)
#define B_SWAP_FLOAT(arg) __swap_float(arg)
#define B_SWAP_INT64(arg) __swap_int64(arg)
#define B_SWAP_INT32(arg) __swap_int32(arg)
#define B_SWAP_INT16(arg) __swap_int16(arg)
#if BYTE_ORDER == __LITTLE_ENDIAN
/* Host is little endian */
#define B_HOST_IS_LENDIAN 1
#define B_HOST_IS_BENDIAN 0
/* Host native to little endian */
#define B_HOST_TO_LENDIAN_DOUBLE(arg) (double)(arg)
#define B_HOST_TO_LENDIAN_FLOAT(arg) (float)(arg)
#define B_HOST_TO_LENDIAN_INT64(arg) (uint64)(arg)
#define B_HOST_TO_LENDIAN_INT32(arg) (uint32)(arg)
#define B_HOST_TO_LENDIAN_INT16(arg) (uint16)(arg)
/* Little endian to host native */
#define B_LENDIAN_TO_HOST_DOUBLE(arg) (double)(arg)
#define B_LENDIAN_TO_HOST_FLOAT(arg) (float)(arg)
#define B_LENDIAN_TO_HOST_INT64(arg) (uint64)(arg)
#define B_LENDIAN_TO_HOST_INT32(arg) (uint32)(arg)
#define B_LENDIAN_TO_HOST_INT16(arg) (uint16)(arg)
/* Host native to big endian */
#define B_HOST_TO_BENDIAN_DOUBLE(arg) __swap_double(arg)
#define B_HOST_TO_BENDIAN_FLOAT(arg) __swap_float(arg)
#define B_HOST_TO_BENDIAN_INT64(arg) __swap_int64(arg)
#define B_HOST_TO_BENDIAN_INT32(arg) __swap_int32(arg)
#define B_HOST_TO_BENDIAN_INT16(arg) __swap_int16(arg)
/* Big endian to host native */
#define B_BENDIAN_TO_HOST_DOUBLE(arg) __swap_double(arg)
#define B_BENDIAN_TO_HOST_FLOAT(arg) __swap_float(arg)
#define B_BENDIAN_TO_HOST_INT64(arg) __swap_int64(arg)
#define B_BENDIAN_TO_HOST_INT32(arg) __swap_int32(arg)
#define B_BENDIAN_TO_HOST_INT16(arg) __swap_int16(arg)
#else /* BYTE_ORDER */
/* Host is big endian */
#define B_HOST_IS_LENDIAN 0
#define B_HOST_IS_BENDIAN 1
/* Host native to little endian */
#define B_HOST_TO_LENDIAN_DOUBLE(arg) __swap_double(arg)
#define B_HOST_TO_LENDIAN_FLOAT(arg) __swap_float(arg)
#define B_HOST_TO_LENDIAN_INT64(arg) __swap_int64(arg)
#define B_HOST_TO_LENDIAN_INT32(arg) __swap_int32(arg)
#define B_HOST_TO_LENDIAN_INT16(arg) __swap_int16(arg)
/* Little endian to host native */
#define B_LENDIAN_TO_HOST_DOUBLE(arg) __swap_double(arg)
#define B_LENDIAN_TO_HOST_FLOAT(arg) __swap_float(arg)
#define B_LENDIAN_TO_HOST_INT64(arg) __swap_int64(arg)
#define B_LENDIAN_TO_HOST_INT32(arg) __swap_int32(arg)
#define B_LENDIAN_TO_HOST_INT16(arg) __swap_int16(arg)
/* Host native to big endian */
#define B_HOST_TO_BENDIAN_DOUBLE(arg) (double)(arg)
#define B_HOST_TO_BENDIAN_FLOAT(arg) (float)(arg)
#define B_HOST_TO_BENDIAN_INT64(arg) (uint64)(arg)
#define B_HOST_TO_BENDIAN_INT32(arg) (uint32)(arg)
#define B_HOST_TO_BENDIAN_INT16(arg) (uint16)(arg)
/* Big endian to host native */
#define B_BENDIAN_TO_HOST_DOUBLE(arg) (double)(arg)
#define B_BENDIAN_TO_HOST_FLOAT(arg) (float)(arg)
#define B_BENDIAN_TO_HOST_INT64(arg) (uint64)(arg)
#define B_BENDIAN_TO_HOST_INT32(arg) (uint32)(arg)
#define B_BENDIAN_TO_HOST_INT16(arg) (uint16)(arg)
#endif /* BYTE_ORDER */
#ifdef __cplusplus
extern "C" {
#endif
extern status_t swap_data(type_code type, void *data, size_t length,
swap_action action);
extern bool is_type_swapped(type_code type);
/* Private implementations */
extern double __swap_double(double arg);
extern float __swap_float(float arg);
extern uint64 __swap_int64(uint64 arg);
extern uint32 __swap_int32(uint32 arg);
extern uint16 __swap_int16(uint16 arg);
#ifdef __cplusplus
}
#endif
#endif /* _BYTEORDER_H */
#include <../os/support/ByteOrder.h>

View File

@ -1,165 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: DataIO.cpp
// Author(s): Ingo Weinhold (bonefish@users.sf.net)
// Stefano Ceccherini (burton666@libero.it)
// The Storage Team
// Description: Pure virtual BDataIO and BPositionIO classes provide
// the protocol for Read()/Write()/Seek().
//
// BMallocIO and BMemoryIO classes implement the protocol,
// as does BFile in the Storage Kit.
//------------------------------------------------------------------------------
#ifndef _DATA_IO_H
#define _DATA_IO_H
#include <SupportDefs.h>
// DataIO
class BDataIO {
public:
BDataIO();
virtual ~BDataIO();
virtual ssize_t Read(void *buffer, size_t size) = 0;
virtual ssize_t Write(const void *buffer, size_t size) = 0;
private:
BDataIO(const BDataIO &);
BDataIO &operator=(const BDataIO &);
virtual void _ReservedDataIO1();
virtual void _ReservedDataIO2();
virtual void _ReservedDataIO3();
virtual void _ReservedDataIO4();
virtual void _ReservedDataIO5();
virtual void _ReservedDataIO6();
virtual void _ReservedDataIO7();
virtual void _ReservedDataIO8();
virtual void _ReservedDataIO9();
virtual void _ReservedDataIO10();
virtual void _ReservedDataIO11();
virtual void _ReservedDataIO12();
uint32 _reserved[2];
};
// BPositionIO
class BPositionIO : public BDataIO {
public:
BPositionIO();
virtual ~BPositionIO();
virtual ssize_t Read(void *buffer, size_t size);
virtual ssize_t Write(const void *buffer, size_t size);
virtual ssize_t ReadAt(off_t position, void *buffer, size_t size) = 0;
virtual ssize_t WriteAt(off_t position, const void *buffer,
size_t size) = 0;
virtual off_t Seek(off_t position, uint32 seekMode) = 0;
virtual off_t Position() const = 0;
virtual status_t SetSize(off_t size);
private:
virtual void _ReservedPositionIO1();
virtual void _ReservedPositionIO2();
virtual void _ReservedPositionIO3();
virtual void _ReservedPositionIO4();
virtual void _ReservedPositionIO5();
virtual void _ReservedPositionIO6();
virtual void _ReservedPositionIO7();
virtual void _ReservedPositionIO8();
virtual void _ReservedPositionIO9();
virtual void _ReservedPositionIO10();
virtual void _ReservedPositionIO11();
virtual void _ReservedPositionIO12();
uint32 _reserved[2];
};
// BMemoryIO
class BMemoryIO : public BPositionIO {
public:
BMemoryIO(void *data, size_t len);
BMemoryIO(const void *data, size_t len);
virtual ~BMemoryIO();
virtual ssize_t ReadAt(off_t position, void *buffer, size_t size);
virtual ssize_t WriteAt(off_t position, const void *buffer, size_t size);
virtual off_t Seek(off_t position, uint32 seekMode);
virtual off_t Position() const;
virtual status_t SetSize(off_t size);
private:
BMemoryIO(const BMemoryIO &);
BMemoryIO &operator=(const BMemoryIO &);
virtual void _ReservedMemoryIO1();
virtual void _ReservedMemoryIO2();
bool fReadOnly;
char *fBuf;
size_t fLen;
size_t fPhys;
size_t fPos;
uint32 _reserved[1];
};
// BMallocIO
class BMallocIO : public BPositionIO {
public:
BMallocIO();
virtual ~BMallocIO();
virtual ssize_t ReadAt(off_t position, void *buffer, size_t size);
virtual ssize_t WriteAt(off_t position, const void *buffer, size_t size);
virtual off_t Seek(off_t position, uint32 seekMode);
virtual off_t Position() const;
virtual status_t SetSize(off_t size);
void SetBlockSize(size_t blockSize);
const void *Buffer() const;
size_t BufferLength() const;
private:
BMallocIO(const BMallocIO &);
BMallocIO &operator=(const BMallocIO &);
virtual void _ReservedMallocIO1();
virtual void _ReservedMallocIO2();
size_t fBlockSize;
size_t fMallocSize;
size_t fLength;
char *fData;
off_t fPosition;
uint32 _reserved[1];
};
#endif
#include <../os/support/DataIO.h>

View File

@ -1,114 +1 @@
/******************************************************************************
/
/ File: Debug.h
/
/ Description: Compile time and runtime switchable debug macros.
/
/ Copyright 1993-98, Be Incorporated
/
******************************************************************************/
#ifndef _DEBUG_H
#define _DEBUG_H
#include <BeBuild.h>
#include <SupportDefs.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <OS.h>
/*------------------------------*/
/*----- Private... -------------*/
#ifdef __cplusplus
extern "C" {
#endif
extern _IMPEXP_ROOT bool _rtDebugFlag;
_IMPEXP_ROOT bool _debugFlag(void);
_IMPEXP_ROOT bool _setDebugFlag(bool);
_IMPEXP_ROOT int _debugPrintf(const char *, ...);
_IMPEXP_ROOT int _sPrintf(const char *, ...);
_IMPEXP_ROOT int _xdebugPrintf(const char *, ...);
_IMPEXP_ROOT int _debuggerAssert(const char *, int, char *);
#ifdef __cplusplus
}
#endif
/*-------- ...to here ----------*/
/*-------------------------------------------------------------*/
/*----- Debug macros ------------------------------------------*/
#if DEBUG
#define SET_DEBUG_ENABLED(FLAG) _setDebugFlag(FLAG)
#define IS_DEBUG_ENABLED() _debugFlag()
#define SERIAL_PRINT(ARGS) _sPrintf ARGS
#define PRINT(ARGS) _debugPrintf ARGS
#define PRINT_OBJECT(OBJ) if (_rtDebugFlag) { \
PRINT(("%s\t", #OBJ)); \
(OBJ).PrintToStream(); \
} ((void) 0)
#define TRACE() _debugPrintf("File: %s, Line: %d, Thread: %d\n", \
__FILE__, __LINE__, find_thread(NULL))
#define SERIAL_TRACE() _sPrintf("File: %s, Line: %d, Thread: %d\n", \
__FILE__, __LINE__, find_thread(NULL))
#define DEBUGGER(MSG) if (_rtDebugFlag) debugger(MSG)
#if !defined(ASSERT)
#define ASSERT(E) (!(E) ? _debuggerAssert(__FILE__,__LINE__, #E) \
: (int)0)
#endif
#define ASSERT_WITH_MESSAGE(expr, msg) \
(!(expr) ? _debuggerAssert( __FILE__,__LINE__, msg) \
: (int)0)
#define TRESPASS() DEBUGGER("Should not be here");
#define DEBUG_ONLY(arg) arg
#else /* DEBUG == 0 */
#define SET_DEBUG_ENABLED(FLAG) (void)0
#define IS_DEBUG_ENABLED() (void)0
#define SERIAL_PRINT(ARGS) (void)0
#define PRINT(ARGS) (void)0
#define PRINT_OBJECT(OBJ) (void)0
#define TRACE() (void)0
#define SERIAL_TRACE() (void)0
#define DEBUGGER(MSG) (void)0
#if !defined(ASSERT)
#define ASSERT(E) (void)0
#endif
#define ASSERT_WITH_MESSAGE(expr, msg) \
(void)0
#define TRESPASS() (void)0
#define DEBUG_ONLY(x)
#endif
#if !__MWERKS__
// STATIC_ASSERT is a compile-time check that can be used to
// verify static expressions such as: STATIC_ASSERT(sizeof(int64) == 8);
#define STATIC_ASSERT(x) \
do { \
struct __staticAssertStruct__ { \
char __static_assert_failed__[2*(x) - 1]; \
}; \
} while (false)
#else
#define STATIC_ASSERT(x)
// the STATIC_ASSERT above doesn't work too well with mwcc because
// of scoping bugs; for now make it do nothing
#endif
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
#endif /* _DEBUG_H */
#include <../os/support/Debug.h>

View File

@ -1,36 +1 @@
// Modified BeOS header. Just here to be able to compile and test BPath.
// To be replaced by the OpenBeOS version to be provided by the IK Team.
#ifndef __sk_flattenable_h__
#define __sk_flattenable_h__
#include <SupportDefs.h>
/*-------------------------------------------------------------*/
/*----- BFlattenable class ------------------------------------*/
class BFlattenable {
public:
virtual bool IsFixedSize() const = 0;
virtual type_code TypeCode() const = 0;
virtual ssize_t FlattenedSize() const = 0;
virtual status_t Flatten(void *buffer, ssize_t size) const = 0;
virtual bool AllowsTypeCode(type_code code) const;
virtual status_t Unflatten(type_code c, const void *buf, ssize_t size) = 0;
virtual ~BFlattenable(); // was a reserved virtual in R4.0
/*----- Private or reserved ---------------*/
private:
void _ReservedFlattenable1();
virtual void _ReservedFlattenable2();
virtual void _ReservedFlattenable3();
};
/*-------------------------------------------------------------*/
/*-------------------------------------------------------------*/
#endif // __sk_flattenable_h__
#include <../os/support/Flattenable.h>

View File

@ -1,98 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: List.h
// Author(s): The Storage kit Team
// Description: BList class provides storage for pointers.
// Not thread safe..
//------------------------------------------------------------------------------
#ifndef _BE_LIST_H
#define _BE_LIST_H
#include <SupportDefs.h>
/*----- BList class --------------------------------------*/
class BList {
public:
BList(int32 count = 20);
BList(const BList& anotherList);
virtual ~BList();
BList& operator =(const BList &);
/* Adding and removing items. */
bool AddItem(void *item, int32 index);
bool AddItem(void *item);
bool AddList(const BList *list, int32 index);
bool AddList(const BList *list);
bool RemoveItem(void *item);
void *RemoveItem(int32 index);
bool RemoveItems(int32 index, int32 count);
bool ReplaceItem(int32 index, void *newItem);
void MakeEmpty();
/* Reordering items. */
void SortItems(int (*compareFunc)(const void *, const void *));
bool SwapItems(int32 indexA, int32 indexB);
bool MoveItem(int32 fromIndex, int32 toIndex);
/* Retrieving items. */
void *ItemAt(int32 index) const;
void *FirstItem() const;
/* Be careful when using this function, since it doesn't */
/* check if the index you pass is valid, and can lead to */
/* unexpected results when it isn't. */
void *ItemAtFast(int32) const;
void *LastItem() const;
void *Items() const;
/* Querying the list. */
bool HasItem(void *item) const;
int32 IndexOf(void *item) const;
int32 CountItems() const;
bool IsEmpty() const;
/* Iterating over the list. */
void DoForEach(bool (*func)(void *));
void DoForEach(bool (*func)(void *, void *), void *arg2);
/*----- Private or reserved ---------------*/
private:
virtual void _ReservedList1();
virtual void _ReservedList2();
// return type differs from BeOS version
bool _ResizeArray(int32 count);
private:
void** fObjectList;
int32 fPhysicalSize;
int32 fItemCount;
int32 fBlockSize;
int32 fResizeThreshold;
uint32 _reserved[1];
};
#endif // _BE_LIST_H
#include <../os/support/List.h>

View File

@ -1,62 +1 @@
//
// $Id: Locker.h 10 2002-07-09 12:24:59Z ejakowatz $
//
// This is the BLocker interface for OpenBeOS. It has been created to
// be source and binary compatible with the BeOS version of BLocker.
//
#ifndef _OPENBEOS_LOCKER_H
#define _OPENBEOS_LOCKER_H
#include <OS.h>
#include <SupportDefs.h>
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
class BLocker {
public:
BLocker();
BLocker(const char *name);
BLocker(bool benaphore_style);
BLocker(const char *name, bool benaphore_style);
// The following constructor is not documented in the BeBook
// and is only listed here to ensure binary compatibility.
// DO NOT USE THIS CONSTRUCTOR!
BLocker(const char *name, bool benaphore_style, bool);
virtual ~BLocker();
bool Lock(void);
status_t LockWithTimeout(bigtime_t timeout);
void Unlock(void);
thread_id LockingThread(void) const;
bool IsLocked(void) const;
int32 CountLocks(void) const;
int32 CountLockRequests(void) const;
sem_id Sem(void) const;
private:
void InitLocker(const char *name, bool benaphore_style);
bool AcquireLock(bigtime_t timeout, status_t *error);
int32 fBenaphoreCount;
sem_id fSemaphoreID;
thread_id fLockOwner;
int32 fRecursiveCount;
// Reserved space for future changes to BLocker
int32 fReservedSpace[4];
};
#ifdef USE_OPENBEOS_NAMESPACE
}
#endif
#endif // _OPENBEOS_LOCKER_H
#include <../os/support/Locker.h>

View File

@ -0,0 +1 @@
#include <../os/support/ObjectList.h>

View File

@ -1,572 +1 @@
/*
* Copyright 2001-2010, Haiku Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef __BSTRING__
#define __BSTRING__
#include <BeBuild.h>
#include <SupportDefs.h>
#include <string.h>
class BStringRef;
class BString {
public:
BString();
BString(const char* string);
BString(const BString& string);
BString(const char* string, int32 maxLength);
~BString();
// Access
const char* String() const;
int32 Length() const;
int32 CountChars() const;
int32 CountBytes(int32 fromCharOffset,
int32 charCount) const;
// Assignment
BString& operator=(const BString& string);
BString& operator=(const char* string);
BString& operator=(char c);
BString& SetTo(const char* string);
BString& SetTo(const char* string, int32 maxLength);
BString& SetTo(const BString& string);
BString& Adopt(BString& from);
BString& SetTo(const BString& string, int32 maxLength);
BString& Adopt(BString& from, int32 maxLength);
BString& SetTo(char c, int32 count);
BString& SetToChars(const char* string, int32 charCount);
BString& SetToChars(const BString& string, int32 charCount);
BString& AdoptChars(BString& from, int32 charCount);
// Substring copying
BString& CopyInto(BString& into, int32 fromOffset,
int32 length) const;
void CopyInto(char* into, int32 fromOffset,
int32 length) const;
BString& CopyCharsInto(BString& into, int32 fromCharOffset,
int32 charCount) const;
bool CopyCharsInto(char* into, int32* intoLength,
int32 fromCharOffset, int32 charCount) const;
// Appending
BString& operator+=(const BString& string);
BString& operator+=(const char* string);
BString& operator+=(char c);
BString& Append(const BString& string);
BString& Append(const char* string);
BString& Append(const BString& string, int32 length);
BString& Append(const char* string, int32 length);
BString& Append(char c, int32 count);
BString& AppendChars(const BString& string, int32 charCount);
BString& AppendChars(const char* string, int32 charCount);
// Prepending
BString& Prepend(const char* string);
BString& Prepend(const BString& string);
BString& Prepend(const char* string, int32 length);
BString& Prepend(const BString& string, int32 length);
BString& Prepend(char c, int32 count);
BString& PrependChars(const char* string, int32 charCount);
BString& PrependChars(const BString& string,
int32 charCount);
// Inserting
BString& Insert(const char* string, int32 position);
BString& Insert(const char* string, int32 length,
int32 position);
BString& Insert(const char* string, int32 fromOffset,
int32 length, int32 position);
BString& Insert(const BString& string, int32 position);
BString& Insert(const BString& string, int32 length,
int32 position);
BString& Insert(const BString& string, int32 fromOffset,
int32 length, int32 position);
BString& Insert(char c, int32 count, int32 position);
BString& InsertChars(const char* string, int32 charPosition);
BString& InsertChars(const char* string, int32 charCount,
int32 charPosition);
BString& InsertChars(const char* string,
int32 fromCharOffset, int32 charCount,
int32 charPosition);
BString& InsertChars(const BString& string,
int32 charPosition);
BString& InsertChars(const BString& string, int32 charCount,
int32 charPosition);
BString& InsertChars(const BString& string,
int32 fromCharOffset, int32 charCount,
int32 charPosition);
// Removing
BString& Truncate(int32 newLength, bool lazy = true);
BString& TruncateChars(int32 newCharCount, bool lazy = true);
BString& Remove(int32 from, int32 length);
BString& RemoveChars(int32 fromCharOffset, int32 charCount);
BString& RemoveFirst(const BString& string);
BString& RemoveLast(const BString& string);
BString& RemoveAll(const BString& string);
BString& RemoveFirst(const char* string);
BString& RemoveLast(const char* string);
BString& RemoveAll(const char* string);
BString& RemoveSet(const char* setOfBytesToRemove);
BString& RemoveCharsSet(const char* setOfCharsToRemove);
BString& MoveInto(BString& into, int32 from, int32 length);
void MoveInto(char* into, int32 from, int32 length);
BString& MoveCharsInto(BString& into, int32 fromCharOffset,
int32 charCount);
bool MoveCharsInto(char* into, int32* intoLength,
int32 fromCharOffset, int32 charCount);
// Compare functions
bool operator<(const BString& string) const;
bool operator<=(const BString& string) const;
bool operator==(const BString& string) const;
bool operator>=(const BString& string) const;
bool operator>(const BString& string) const;
bool operator!=(const BString& string) const;
bool operator<(const char* string) const;
bool operator<=(const char* string) const;
bool operator==(const char* string) const;
bool operator>=(const char* string) const;
bool operator>(const char* string) const;
bool operator!=(const char* string) const;
operator const char*() const;
// strcmp()-style compare functions
int Compare(const BString& string) const;
int Compare(const char* string) const;
int Compare(const BString& string, int32 length) const;
int Compare(const char* string, int32 length) const;
int CompareChars(const BString& string,
int32 charCount) const;
int CompareChars(const char* string,
int32 charCount) const;
int ICompare(const BString& string) const;
int ICompare(const char* string) const;
int ICompare(const BString& string, int32 length) const;
int ICompare(const char* string, int32 length) const;
// Searching
int32 FindFirst(const BString& string) const;
int32 FindFirst(const char* string) const;
int32 FindFirst(const BString& string,
int32 fromOffset) const;
int32 FindFirst(const char* string,
int32 fromOffset) const;
int32 FindFirst(char c) const;
int32 FindFirst(char c, int32 fromOffset) const;
int32 FindFirstChars(const BString& string,
int32 fromCharOffset) const;
int32 FindFirstChars(const char* string,
int32 fromCharOffset) const;
int32 FindLast(const BString& string) const;
int32 FindLast(const char* string) const;
int32 FindLast(const BString& string,
int32 beforeOffset) const;
int32 FindLast(const char* string,
int32 beforeOffset) const;
int32 FindLast(char c) const;
int32 FindLast(char c, int32 beforeOffset) const;
int32 FindLastChars(const BString& string,
int32 beforeCharOffset) const;
int32 FindLastChars(const char* string,
int32 beforeCharOffset) const;
int32 IFindFirst(const BString& string) const;
int32 IFindFirst(const char* string) const;
int32 IFindFirst(const BString& string,
int32 fromOffset) const;
int32 IFindFirst(const char* string,
int32 fromOffset) const;
int32 IFindLast(const BString& string) const;
int32 IFindLast(const char* string) const;
int32 IFindLast(const BString& string,
int32 beforeOffset) const;
int32 IFindLast(const char* string,
int32 beforeOffset) const;
// Replacing
BString& ReplaceFirst(char replaceThis, char withThis);
BString& ReplaceLast(char replaceThis, char withThis);
BString& ReplaceAll(char replaceThis, char withThis,
int32 fromOffset = 0);
BString& Replace(char replaceThis, char withThis,
int32 maxReplaceCount, int32 fromOffset = 0);
BString& ReplaceFirst(const char* replaceThis,
const char* withThis);
BString& ReplaceLast(const char* replaceThis,
const char* withThis);
BString& ReplaceAll(const char* replaceThis,
const char* withThis, int32 fromOffset = 0);
BString& Replace(const char* replaceThis,
const char* withThis, int32 maxReplaceCount,
int32 fromOffset = 0);
BString& ReplaceAllChars(const char* replaceThis,
const char* withThis, int32 fromCharOffset);
BString& ReplaceChars(const char* replaceThis,
const char* withThis, int32 maxReplaceCount,
int32 fromCharOffset);
BString& IReplaceFirst(char replaceThis, char withThis);
BString& IReplaceLast(char replaceThis, char withThis);
BString& IReplaceAll(char replaceThis, char withThis,
int32 fromOffset = 0);
BString& IReplace(char replaceThis, char withThis,
int32 maxReplaceCount, int32 fromOffset = 0);
BString& IReplaceFirst(const char* replaceThis,
const char* withThis);
BString& IReplaceLast(const char* replaceThis,
const char* withThis);
BString& IReplaceAll(const char* replaceThis,
const char* withThis, int32 fromOffset = 0);
BString& IReplace(const char* replaceThis,
const char* withThis, int32 maxReplaceCount,
int32 fromOffset = 0);
BString& ReplaceSet(const char* setOfBytes, char with);
BString& ReplaceSet(const char* setOfBytes,
const char* with);
BString& ReplaceCharsSet(const char* setOfChars,
const char* with);
// Unchecked char access
char operator[](int32 index) const;
#if __GNUC__ > 3
BStringRef operator[](int32 index);
#else
char& operator[](int32 index);
#endif
// Checked char access
char ByteAt(int32 index) const;
const char* CharAt(int32 charIndex, int32* bytes = NULL) const;
bool CharAt(int32 charIndex, char* buffer,
int32* bytes) const;
// Fast low-level manipulation
char* LockBuffer(int32 maxLength);
BString& UnlockBuffer(int32 length = -1);
// Upercase <-> Lowercase
BString& ToLower();
BString& ToUpper();
BString& Capitalize();
BString& CapitalizeEachWord();
// Escaping and De-escaping
BString& CharacterEscape(const char* original,
const char* setOfCharsToEscape,
char escapeWith);
BString& CharacterEscape(const char* setOfCharsToEscape,
char escapeWith);
BString& CharacterDeescape(const char* original,
char escapeChar);
BString& CharacterDeescape(char escapeChar);
// Trimming
BString& Trim();
// Insert
BString& operator<<(const char* string);
BString& operator<<(const BString& string);
BString& operator<<(char c);
BString& operator<<(int value);
BString& operator<<(unsigned int value);
BString& operator<<(unsigned long value);
BString& operator<<(long value);
BString& operator<<(unsigned long long value);
BString& operator<<(long long value);
// float output hardcodes %.2f style formatting
BString& operator<<(float value);
private:
class PosVect;
friend class BStringRef;
// Management
status_t _MakeWritable();
status_t _MakeWritable(int32 length, bool copy);
static char* _Allocate(int32 length);
char* _Resize(int32 length);
void _Init(const char* src, int32 length);
char* _Clone(const char* data, int32 length);
char* _OpenAtBy(int32 offset, int32 length);
char* _ShrinkAtBy(int32 offset, int32 length);
// Data
void _SetLength(int32 length);
bool _DoAppend(const char* string, int32 length);
bool _DoPrepend(const char* string, int32 length);
bool _DoInsert(const char* string, int32 offset,
int32 length);
// Search
int32 _ShortFindAfter(const char* string,
int32 length) const;
int32 _FindAfter(const char* string, int32 offset,
int32 length) const;
int32 _IFindAfter(const char* string, int32 offset,
int32 length) const;
int32 _FindBefore(const char* string, int32 offset,
int32 length) const;
int32 _IFindBefore(const char* string, int32 offset,
int32 length) const;
// Escape
BString& _DoCharacterEscape(const char* string,
const char *setOfCharsToEscape, char escapeChar);
BString& _DoCharacterDeescape(const char* string,
char escapeChar);
// Replace
BString& _DoReplace(const char* findThis,
const char* replaceWith, int32 maxReplaceCount,
int32 fromOffset, bool ignoreCase);
void _ReplaceAtPositions(const PosVect* positions,
int32 searchLength, const char* with,
int32 withLength);
private:
vint32& _ReferenceCount();
const vint32& _ReferenceCount() const;
bool _IsShareable() const;
void _FreePrivateData();
char* fPrivateData;
};
// Commutative compare operators
bool operator<(const char* a, const BString& b);
bool operator<=(const char* a, const BString& b);
bool operator==(const char* a, const BString& b);
bool operator>(const char* a, const BString& b);
bool operator>=(const char* a, const BString& b);
bool operator!=(const char* a, const BString& b);
// Non-member compare for sorting, etc.
int Compare(const BString& a, const BString& b);
int ICompare(const BString& a, const BString& b);
int Compare(const BString* a, const BString* b);
int ICompare(const BString* a, const BString* b);
inline int32
BString::Length() const
{
// the most significant bit is reserved; accessing
// it in any way will cause the computer to explode
return fPrivateData ? (*(((int32 *)fPrivateData) - 1) & 0x7fffffff) : 0;
}
inline const char*
BString::String() const
{
if (!fPrivateData)
return "";
return fPrivateData;
}
inline BString &
BString::SetTo(const char* string)
{
return operator=(string);
}
inline char
BString::operator[](int32 index) const
{
return fPrivateData[index];
}
inline char
BString::ByteAt(int32 index) const
{
if (!fPrivateData || index < 0 || index >= Length())
return 0;
return fPrivateData[index];
}
inline BString &
BString::operator+=(const BString &string)
{
_DoAppend(string.String(), string.Length());
return *this;
}
inline BString &
BString::Append(const BString &string)
{
_DoAppend(string.String(), string.Length());
return *this;
}
inline BString &
BString::Append(const char* string)
{
return operator+=(string);
}
inline bool
BString::operator==(const BString &string) const
{
return strcmp(String(), string.String()) == 0;
}
inline bool
BString::operator<(const BString &string) const
{
return strcmp(String(), string.String()) < 0;
}
inline bool
BString::operator<=(const BString &string) const
{
return strcmp(String(), string.String()) <= 0;
}
inline bool
BString::operator>=(const BString &string) const
{
return strcmp(String(), string.String()) >= 0;
}
inline bool
BString::operator>(const BString &string) const
{
return strcmp(String(), string.String()) > 0;
}
inline bool
BString::operator!=(const BString &string) const
{
return strcmp(String(), string.String()) != 0;
}
inline bool
BString::operator!=(const char* string) const
{
return !operator==(string);
}
inline
BString::operator const char*() const
{
return String();
}
inline bool
operator<(const char *str, const BString &string)
{
return string > str;
}
inline bool
operator<=(const char *str, const BString &string)
{
return string >= str;
}
inline bool
operator==(const char *str, const BString &string)
{
return string == str;
}
inline bool
operator>(const char *str, const BString &string)
{
return string < str;
}
inline bool
operator>=(const char *str, const BString &string)
{
return string <= str;
}
inline bool
operator!=(const char *str, const BString &string)
{
return string != str;
}
// #pragma mark - BStringRef
class BStringRef {
public:
BStringRef(BString& string, int32 position);
~BStringRef() {}
operator char() const;
char* operator&();
const char* operator&() const;
BStringRef& operator=(char c);
BStringRef& operator=(const BStringRef& rc);
private:
BString& fString;
int32 fPosition;
};
#endif // __BSTRING__
#include <../os/support/String.h>

View File

@ -1,242 +1,2 @@
/*
* Copyright 2004-2010, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Author:
* Erik Jaesler (erik@cgsoftware.com)
*/
#ifndef _SUPPORT_DEFS_H
#define _SUPPORT_DEFS_H
#include <config_build/types.h>
#include <BeBuild.h>
#include <Errors.h>
#include <inttypes.h>
#include <sys/types.h>
/* fixed-size integer types */
typedef __haiku_int8 int8;
typedef __haiku_uint8 uint8;
typedef __haiku_int16 int16;
typedef __haiku_uint16 uint16;
typedef __haiku_int32 int32;
typedef __haiku_uint32 uint32;
typedef __haiku_int64 int64;
typedef __haiku_uint64 uint64;
/* shorthand types */
typedef volatile int8 vint8;
typedef volatile uint8 vuint8;
typedef volatile int16 vint16;
typedef volatile uint16 vuint16;
typedef volatile int32 vint32;
typedef volatile uint32 vuint32;
typedef volatile int64 vint64;
typedef volatile uint64 vuint64;
typedef volatile long vlong;
typedef volatile int vint;
typedef volatile short vshort;
typedef volatile char vchar;
typedef volatile unsigned long vulong;
typedef volatile unsigned int vuint;
typedef volatile unsigned short vushort;
typedef volatile unsigned char vuchar;
typedef unsigned char uchar;
typedef unsigned short unichar;
/* descriptive types */
typedef int32 status_t;
typedef int64 bigtime_t;
typedef uint32 type_code;
typedef uint32 perform_code;
#ifdef HAIKU_HOST_PLATFORM_64_BIT
typedef uint64 phys_addr_t;
#else
typedef uint32 phys_addr_t;
#endif
typedef phys_addr_t phys_size_t;
typedef addr_t generic_addr_t;
typedef size_t generic_size_t;
/* printf()/scanf() format strings for [u]int* types */
#define B_PRId8 PRId8
#define B_PRIi8 PRIi8
#define B_PRId16 PRId16
#define B_PRIi16 PRIi16
#define B_PRId32 PRId32
#define B_PRIi32 PRIi32
#define B_PRId64 PRId64
#define B_PRIi64 PRIi64
#define B_PRIu8 PRIu8
#define B_PRIo8 PRIo8
#define B_PRIx8 PRIx8
#define B_PRIX8 PRIX8
#define B_PRIu16 PRIu16
#define B_PRIo16 PRIo16
#define B_PRIx16 PRIx16
#define B_PRIX16 PRIX16
#define B_PRIu32 PRIu32
#define B_PRIo32 PRIo32
#define B_PRIx32 PRIx32
#define B_PRIX32 PRIX32
#define B_PRIu64 PRIu64
#define B_PRIo64 PRIo64
#define B_PRIx64 PRIx64
#define B_PRIX64 PRIX64
#define B_SCNd8 SCNd8
#define B_SCNi8 SCNi8
#define B_SCNd16 SCNd16
#define B_SCNi16 SCNi16
#define B_SCNd32 SCNd32
#define B_SCNi32 SCNi32
#define B_SCNd64 SCNd64
#define B_SCNi64 SCNi64
#define B_SCNu8 SCNu8
#define B_SCNo8 SCNo8
#define B_SCNx8 SCNx8
#define B_SCNu16 SCNu16
#define B_SCNu16 SCNu16
#define B_SCNx16 SCNx16
#define B_SCNu32 SCNu32
#define B_SCNo32 SCNo32
#define B_SCNx32 SCNx32
#define B_SCNu64 SCNu64
#define B_SCNo64 SCNo64
#define B_SCNx64 SCNx64
/* printf() format strings for some standard types */
/* addr_t, size_t, ssize_t */
#ifdef HAIKU_HOST_PLATFORM_64_BIT
# define B_PRIuADDR B_PRIu64
# define B_PRIoADDR B_PRIo64
# define B_PRIxADDR B_PRIx64
# define B_PRIXADDR B_PRIX64
# define B_PRIuSIZE B_PRIu64
# define B_PRIoSIZE B_PRIo64
# define B_PRIxSIZE B_PRIx64
# define B_PRIXSIZE B_PRIX64
# define B_PRIdSSIZE B_PRId64
# define B_PRIiSSIZE B_PRIi64
#else
# define B_PRIuADDR B_PRIu32
# define B_PRIoADDR B_PRIo32
# define B_PRIxADDR B_PRIx32
# define B_PRIXADDR B_PRIX32
# define B_PRIuSIZE B_PRIu32
# define B_PRIoSIZE B_PRIo32
# define B_PRIxSIZE B_PRIx32
# define B_PRIXSIZE B_PRIX32
# define B_PRIdSSIZE B_PRId32
# define B_PRIiSSIZE B_PRIi32
#endif
/* phys_addr_t */
#ifdef HAIKU_HOST_PLATFORM_64_BIT
# define B_PRIuPHYSADDR B_PRIu64
# define B_PRIoPHYSADDR B_PRIo64
# define B_PRIxPHYSADDR B_PRIx64
# define B_PRIXPHYSADDR B_PRIX64
#else
# define B_PRIuPHYSADDR B_PRIu32
# define B_PRIoPHYSADDR B_PRIo32
# define B_PRIxPHYSADDR B_PRIx32
# define B_PRIXPHYSADDR B_PRIX32
#endif
/* generic_addr_t */
#define B_PRIuGENADDR B_PRIuADDR
#define B_PRIoGENADDR B_PRIoADDR
#define B_PRIxGENADDR B_PRIxADDR
#define B_PRIXGENADDR B_PRIXADDR
/* off_t */
#define B_PRIdOFF B_PRId64
#define B_PRIiOFF B_PRIi64
/* dev_t */
#define B_PRIdDEV B_PRId32
#define B_PRIiDEV B_PRIi32
/* ino_t */
#define B_PRIdINO B_PRId64
#define B_PRIiINO B_PRIi64
/* time_t */
#define B_PRIdTIME B_PRId32
#define B_PRIiTIME B_PRIi32
/* Empty string ("") */
#ifdef __cplusplus
extern const char *B_EMPTY_STRING;
#endif
/* min and max comparisons */
#ifndef __cplusplus
# ifndef min
# define min(a,b) ((a)>(b)?(b):(a))
# endif
# ifndef max
# define max(a,b) ((a)>(b)?(a):(b))
# endif
#endif
/* min() and max() are functions in C++ */
#define min_c(a,b) ((a)>(b)?(b):(a))
#define max_c(a,b) ((a)>(b)?(a):(b))
/* Grandfathering */
#ifndef __cplusplus
# include <stdbool.h>
#endif
#ifndef NULL
# define NULL (0)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Atomic functions; previous value is returned */
extern int32 atomic_set(vint32 *value, int32 newValue);
extern int32 atomic_test_and_set(vint32 *value, int32 newValue, int32 testAgainst);
extern int32 atomic_add(vint32 *value, int32 addValue);
extern int32 atomic_and(vint32 *value, int32 andValue);
extern int32 atomic_or(vint32 *value, int32 orValue);
extern int32 atomic_get(vint32 *value);
extern int64 atomic_set64(vint64 *value, int64 newValue);
extern int64 atomic_test_and_set64(vint64 *value, int64 newValue, int64 testAgainst);
extern int64 atomic_add64(vint64 *value, int64 addValue);
extern int64 atomic_and64(vint64 *value, int64 andValue);
extern int64 atomic_or64(vint64 *value, int64 orValue);
extern int64 atomic_get64(vint64 *value);
/* Other stuff */
extern void* get_stack_frame(void);
#ifdef __cplusplus
}
#endif
/* Obsolete or discouraged API */
/* use 'true' and 'false' */
#ifndef FALSE
# define FALSE 0
#endif
#ifndef TRUE
# define TRUE 1
#endif
#endif /* _SUPPORT_DEFS_H */
#include <../os/support/SupportDefs.h>

View File

@ -1,78 +1 @@
/*
* Copyright 2005-2007, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Author:
* Erik Jaesler (erik@cgsoftware.com)
*/
#ifndef _TYPE_CONSTANTS_H
#define _TYPE_CONSTANTS_H
#include <BeBuild.h>
enum {
B_ANY_TYPE = 'ANYT',
B_ATOM_TYPE = 'ATOM',
B_ATOMREF_TYPE = 'ATMR',
B_BOOL_TYPE = 'BOOL',
B_CHAR_TYPE = 'CHAR',
B_COLOR_8_BIT_TYPE = 'CLRB',
B_DOUBLE_TYPE = 'DBLE',
B_FLOAT_TYPE = 'FLOT',
B_GRAYSCALE_8_BIT_TYPE = 'GRYB',
B_INT16_TYPE = 'SHRT',
B_INT32_TYPE = 'LONG',
B_INT64_TYPE = 'LLNG',
B_INT8_TYPE = 'BYTE',
B_LARGE_ICON_TYPE = 'ICON',
B_MEDIA_PARAMETER_GROUP_TYPE = 'BMCG',
B_MEDIA_PARAMETER_TYPE = 'BMCT',
B_MEDIA_PARAMETER_WEB_TYPE = 'BMCW',
B_MESSAGE_TYPE = 'MSGG',
B_MESSENGER_TYPE = 'MSNG',
B_MIME_TYPE = 'MIME',
B_MINI_ICON_TYPE = 'MICN',
B_MONOCHROME_1_BIT_TYPE = 'MNOB',
B_OBJECT_TYPE = 'OPTR',
B_OFF_T_TYPE = 'OFFT',
B_PATTERN_TYPE = 'PATN',
B_POINTER_TYPE = 'PNTR',
B_POINT_TYPE = 'BPNT',
B_PROPERTY_INFO_TYPE = 'SCTD',
B_RAW_TYPE = 'RAWT',
B_RECT_TYPE = 'RECT',
B_REF_TYPE = 'RREF',
B_RGB_32_BIT_TYPE = 'RGBB',
B_RGB_COLOR_TYPE = 'RGBC',
B_SIZE_T_TYPE = 'SIZT',
B_SSIZE_T_TYPE = 'SSZT',
B_STRING_TYPE = 'CSTR',
B_TIME_TYPE = 'TIME',
B_UINT16_TYPE = 'USHT',
B_UINT32_TYPE = 'ULNG',
B_UINT64_TYPE = 'ULLG',
B_UINT8_TYPE = 'UBYT',
B_VECTOR_ICON_TYPE = 'VICN',
// deprecated, do not use
B_ASCII_TYPE = 'TEXT' // use B_STRING_TYPE instead
};
// System-wide MIME types for handling URL's
extern const char *B_URL_HTTP; // application/x-vnd.Be.URL.http
extern const char *B_URL_HTTPS; // application/x-vnd.Be.URL.https
extern const char *B_URL_FTP; // application/x-vnd.Be.URL.ftp
extern const char *B_URL_GOPHER; // application/x-vnd.Be.URL.gopher
extern const char *B_URL_MAILTO; // application/x-vnd.Be.URL.mailto
extern const char *B_URL_NEWS; // application/x-vnd.Be.URL.news
extern const char *B_URL_NNTP; // application/x-vnd.Be.URL.nntp
extern const char *B_URL_TELNET; // application/x-vnd.Be.URL.telnet
extern const char *B_URL_RLOGIN; // application/x-vnd.Be.URL.rlogin
extern const char *B_URL_TN3270; // application/x-vnd.Be.URL.tn3270
extern const char *B_URL_WAIS; // application/x-vnd.Be.URL.wais
extern const char *B_URL_FILE; // application/x-vnd.Be.URL.file
#endif // _TYPE_CONSTANTS_H
#include <../os/support/TypeConstants.h>

View File

@ -1,126 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: LooperList.h
// Author(s): Erik Jaesler (erik@cgsoftware.com)
// Description: Maintains a global list of all loopers in a given team.
//------------------------------------------------------------------------------
#ifndef LOOPERLIST_H
#define LOOPERLIST_H
// Standard Includes -----------------------------------------------------------
#include <vector>
// System Includes -------------------------------------------------------------
#include <Locker.h>
#include <OS.h>
#include <SupportDefs.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
class BLooper;
namespace BPrivate {
class BLooperList
{
public:
BLooperList();
bool Lock();
void Unlock();
bool IsLocked();
void AddLooper(BLooper* l);
bool IsLooperValid(const BLooper* l);
bool RemoveLooper(BLooper* l);
void GetLooperList(BList* list);
int32 CountLoopers();
BLooper* LooperAt(int32 index);
BLooper* LooperForThread(thread_id tid);
BLooper* LooperForName(const char* name);
BLooper* LooperForPort(port_id port);
struct LooperData
{
LooperData();
LooperData(BLooper* loop, uint32 i);
LooperData(const LooperData& rhs);
LooperData& operator=(const LooperData& rhs);
BLooper* looper;
uint32 id;
};
private:
static bool EmptySlotPred(LooperData& Data);
struct FindLooperPred
{
FindLooperPred(const BLooper* loop) : looper(loop) {;}
bool operator()(LooperData& Data);
const BLooper* looper;
};
struct FindThreadPred
{
FindThreadPred(thread_id tid) : thread(tid) {;}
bool operator()(LooperData& Data);
thread_id thread;
};
struct FindNamePred
{
FindNamePred(const char* n) : name(n) {;}
bool operator()(LooperData& Data);
const char* name;
};
struct FindPortPred
{
FindPortPred(port_id pid) : port(pid) {;}
bool operator()(LooperData& Data);
port_id port;
};
void AssertLocked();
BLocker fLock;
uint32 fLooperID;
std::vector<LooperData> fData;
};
extern _IMPEXP_BE BLooperList gLooperList;
}
#endif //LOOPERLIST_H
/*
* $Log $
*
* $Id $
*
*/
#include <../private/app/LooperList.h>

View File

@ -1,51 +1 @@
/*
* Copyright 2007, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Michael Lotz <mmlr@mlotz.ch>
*/
#ifndef _MESSAGE_ADAPTER_H_
#define _MESSAGE_ADAPTER_H_
#include <Message.h>
// message formats
#define MESSAGE_FORMAT_R5 'FOB1'
#define MESSAGE_FORMAT_R5_SWAPPED '1BOF'
#define MESSAGE_FORMAT_DANO 'FOB2'
#define MESSAGE_FORMAT_DANO_SWAPPED '2BOF'
#define MESSAGE_FORMAT_HAIKU '1FMH'
#define MESSAGE_FORMAT_HAIKU_SWAPPED 'HMF1'
namespace BPrivate {
class MessageAdapter {
public:
static ssize_t FlattenedSize(uint32 format, const BMessage *from);
static status_t Flatten(uint32 format, const BMessage *from,
char *buffer, ssize_t *size);
static status_t Flatten(uint32 format, const BMessage *from,
BDataIO *stream, ssize_t *size);
static status_t Unflatten(uint32 format, BMessage *into,
const char *buffer);
static status_t Unflatten(uint32 format, BMessage *into,
BDataIO *stream);
private:
static ssize_t _R5FlattenedSize(const BMessage *from);
static status_t _FlattenR5Message(uint32 format, const BMessage *from,
char *buffer, ssize_t *size);
static status_t _UnflattenR5Message(uint32 format, BMessage *into,
BDataIO *stream);
static status_t _UnflattenDanoMessage(uint32 format, BMessage *into,
BDataIO *stream);
};
} // namespace BPrivate
#endif // _MESSAGE_ADAPTER_H_
#include <../private/app/MessageAdapter.h>

View File

@ -1,187 +1 @@
#ifndef _MESSAGE_UTILS_H_
#define _MESSAGE_UTILS_H_
#include <ByteOrder.h>
#include <DataIO.h>
#include <Entry.h>
#include <Message.h>
#include <SupportDefs.h>
namespace BPrivate { // Only putting these here because Be did
status_t entry_ref_flatten(char* buffer, size_t* size, const entry_ref* ref);
status_t entry_ref_unflatten(entry_ref* ref, const char* buffer, size_t size);
status_t entry_ref_swap(char* buffer, size_t size);
uint32 CalculateChecksum(const uint8 *buffer, int32 size);
} // namespace BPrivate
template<class T>
inline void
byte_swap(T &/*data*/)
{
// Specialize for data types which actually swap
}
inline void
write_helper(BDataIO *stream, const void *data, size_t size)
{
status_t error = stream->Write(data, size);
if (error < B_OK)
throw error;
}
class TReadHelper {
public:
TReadHelper(BDataIO *stream)
: fStream(stream),
fError(B_OK),
fSwap(false)
{
}
TReadHelper(BDataIO *stream, bool swap)
: fStream(stream),
fError(B_OK),
fSwap(swap)
{
}
template<class T>
inline void operator()(T &data)
{
fError = fStream->Read((void *)&data, sizeof(T));
if (fError > B_OK) {
if (IsSwapping())
byte_swap(data);
return;
}
if (fError == 0)
fError = B_ERROR;
throw fError;
}
template<class T>
inline void operator()(T data, size_t len)
{
fError = fStream->Read((void *)data, len);
if (fError >= B_OK)
return;
throw fError;
}
status_t Status() { return fError >= B_OK ? B_OK : fError; };
void SetSwap(bool yesNo) { fSwap = yesNo; };
bool IsSwapping() { return fSwap; };
private:
BDataIO *fStream;
status_t fError;
bool fSwap;
};
class TChecksumHelper {
public:
TChecksumHelper(uchar* buffer)
: fBuffer(buffer),
fBufPtr(buffer)
{
}
template<class T>
inline void Cache(const T &data)
{
*((T*)fBufPtr) = data;
fBufPtr += sizeof (T);
}
int32 CheckSum();
private:
uchar *fBuffer;
uchar *fBufPtr;
};
template<>
inline void
byte_swap(double &data)
{
data = __swap_double(data);
}
template<>
inline void
byte_swap(float &data)
{
data = __swap_float(data);
}
template<>
inline void
byte_swap(int64 &data)
{
data = __swap_int64(data);
}
template<>
inline void
byte_swap(uint64 &data)
{
data = __swap_int64(data);
}
template<>
inline void
byte_swap(int32 &data)
{
data = __swap_int32(data);
}
template<>
inline void
byte_swap(uint32 &data)
{
data = __swap_int32(data);
}
template<>
inline void
byte_swap(int16 &data)
{
data = __swap_int16(data);
}
template<>
inline void
byte_swap(uint16 &data)
{
data = __swap_int16(data);
}
template<>
inline void
byte_swap(entry_ref &data)
{
byte_swap(data.device);
byte_swap(data.directory);
}
#endif // _MESSAGE_UTILS_H_
#include <../private/app/MessageUtils.h>

View File

@ -1,177 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: RegistrarDefs.h
// Author(s): Ingo Weinhold (bonefish@users.sf.net)
// Description: API classes - registrar interface.
//------------------------------------------------------------------------------
#ifndef REGISTRAR_DEFS_H
#define REGISTRAR_DEFS_H
#include <Errors.h>
#include <Roster.h>
namespace BPrivate {
// names
extern const char *kRegistrarSignature;
extern const char *kRosterThreadName;
extern const char *kRAppLooperPortName;
extern const char *get_roster_port_name();
// message constants
enum {
// replies
B_REG_SUCCESS = 'rgsu',
B_REG_ERROR = 'rger',
B_REG_RESULT = 'rgrz',
// general requests
B_REG_GET_MIME_MESSENGER = 'rgmm',
B_REG_GET_CLIPBOARD_MESSENGER = 'rgcm',
B_REG_GET_DISK_DEVICE_MESSENGER = 'rgdm',
B_REG_SHUT_DOWN = 'rgsh',
// roster requests
B_REG_ADD_APP = 'rgaa',
B_REG_COMPLETE_REGISTRATION = 'rgcr',
B_REG_IS_APP_PRE_REGISTERED = 'rgip',
B_REG_REMOVE_PRE_REGISTERED_APP = 'rgrp',
B_REG_REMOVE_APP = 'rgra',
B_REG_SET_THREAD_AND_TEAM = 'rgtt',
B_REG_SET_SIGNATURE = 'rgss',
B_REG_GET_APP_INFO = 'rgai',
B_REG_GET_APP_LIST = 'rgal',
B_REG_ACTIVATE_APP = 'rgac',
B_REG_BROADCAST = 'rgbc',
B_REG_START_WATCHING = 'rgwa',
B_REG_STOP_WATCHING = 'rgsw',
B_REG_GET_RECENT_DOCUMENTS = 'rggd',
B_REG_GET_RECENT_FOLDERS = 'rggf',
B_REG_GET_RECENT_APPS = 'rgga',
B_REG_ADD_TO_RECENT_DOCUMENTS = 'rg2d',
B_REG_ADD_TO_RECENT_FOLDERS = 'rg2f',
B_REG_ADD_TO_RECENT_APPS = 'rg2a',
B_REG_CLEAR_RECENT_DOCUMENTS = 'rgxd',
B_REG_CLEAR_RECENT_FOLDERS = 'rgxf',
B_REG_CLEAR_RECENT_APPS = 'rgxa',
B_REG_LOAD_RECENT_LISTS = 'rglr',
B_REG_SAVE_RECENT_LISTS = 'rgsr',
// MIME requests
B_REG_MIME_SET_PARAM = 'rgsp',
B_REG_MIME_DELETE_PARAM = 'rgdp',
B_REG_MIME_START_WATCHING = 'rgwb',
B_REG_MIME_STOP_WATCHING = 'rgwe',
B_REG_MIME_INSTALL = 'rgin',
B_REG_MIME_DELETE = 'rgdl',
B_REG_MIME_GET_INSTALLED_TYPES = 'rgit',
B_REG_MIME_GET_INSTALLED_SUPERTYPES = 'rgis',
B_REG_MIME_GET_SUPPORTING_APPS = 'rgsa',
B_REG_MIME_GET_ASSOCIATED_TYPES = 'rgat',
B_REG_MIME_SNIFF = 'rgsn',
B_REG_MIME_UPDATE_MIME_INFO = 'rgup',
B_REG_MIME_CREATE_APP_META_MIME = 'rgca',
B_REG_MIME_UPDATE_THREAD_FINISHED = 'rgtf',
// message runner requests
B_REG_REGISTER_MESSAGE_RUNNER = 'rgrr',
B_REG_UNREGISTER_MESSAGE_RUNNER = 'rgru',
B_REG_SET_MESSAGE_RUNNER_PARAMS = 'rgrx',
B_REG_GET_MESSAGE_RUNNER_INFO = 'rgri',
// internal registrar messages
B_REG_ROSTER_SANITY_EVENT = 'rgir',
B_REG_SHUTDOWN_FINISHED = 'rgsf',
B_REG_ROSTER_DEVICE_RESCAN = 'rgrs',
// clipboard handler requests
B_REG_ADD_CLIPBOARD = 'rgCa',
B_REG_GET_CLIPBOARD_COUNT = 'rgCc',
B_REG_CLIPBOARD_START_WATCHING = 'rgCw',
B_REG_CLIPBOARD_STOP_WATCHING = 'rgCx',
B_REG_DOWNLOAD_CLIPBOARD = 'rgCd',
B_REG_UPLOAD_CLIPBOARD = 'rgCu',
// disk device request
B_REG_NEXT_DISK_DEVICE = 'rgnx',
B_REG_GET_DISK_DEVICE = 'rgdd',
B_REG_UPDATE_DISK_DEVICE = 'rgud',
B_REG_DEVICE_START_WATCHING = 'rgwd',
B_REG_DEVICE_STOP_WATCHING = 'rgsd',
};
// B_REG_MIME_SET_PARAM "which" constants
enum {
B_REG_MIME_APP_HINT = 'rgmh',
B_REG_MIME_ATTR_INFO = 'rgma',
B_REG_MIME_DESCRIPTION = 'rgmd',
B_REG_MIME_FILE_EXTENSIONS = 'rgmf',
B_REG_MIME_ICON = 'rgmi',
B_REG_MIME_ICON_FOR_TYPE = 'rgm4',
B_REG_MIME_PREFERRED_APP = 'rgmp',
B_REG_MIME_SNIFFER_RULE = 'rgmr',
B_REG_MIME_SUPPORTED_TYPES = 'rgms',
};
// B_REG_UPDATE_DISK_DEVICE "update_policy" constants
enum {
B_REG_DEVICE_UPDATE_CHECK,
B_REG_DEVICE_UPDATE_CHANGED,
B_REG_DEVICE_UPDATE_DEVICE_CHANGED,
};
// type constants
enum {
B_REG_APP_INFO_TYPE = 'rgai', // app_info
};
// error constants
#define B_REGISTRAR_ERROR_BASE (B_ERRORS_END + 1)
enum {
B_REG_ALREADY_REGISTERED = B_REGISTRAR_ERROR_BASE,
// A team tries to register a second time.
B_REG_APP_NOT_REGISTERED,
B_REG_APP_NOT_PRE_REGISTERED,
};
// misc constants
enum {
B_REG_DEFAULT_APP_FLAGS = B_MULTIPLE_LAUNCH | B_ARGV_ONLY
| _B_APP_INFO_RESERVED1_,
B_REG_APP_LOOPER_PORT_CAPACITY = 100,
};
// structs
// a flat app_info -- to be found in B_REG_APP_INFO_TYPE message fields
struct flat_app_info {
app_info info;
char ref_name[B_FILE_NAME_LENGTH + 1];
};
} // namespace BPrivate
#endif // REGISTRAR_DEFS_H
#include <../private/app/RegistrarDefs.h>

View File

@ -1,82 +1 @@
/*
* Copyright 2001-2005, Haiku.
* Distributed under the terms of the MIT License.
*
* Authors:
* Erik Jaesler (erik@cgsoftware.com)
* Axel Dörfler, axeld@pinc-software.de
*/
#ifndef _TOKEN_SPACE_H
#define _TOKEN_SPACE_H
#include <map>
#include <stack>
#include <BeBuild.h>
#include <Locker.h>
#include <SupportDefs.h>
// token types as specified in targets
#define B_PREFERRED_TOKEN -2 /* A little bird told me about this one */
#define B_NULL_TOKEN -1
#define B_ANY_TOKEN 0
// token types in the token list
#define B_HANDLER_TOKEN 1
#define B_SERVER_TOKEN 2
namespace BPrivate {
typedef void (*new_token_callback)(int16, void*);
typedef void (*remove_token_callback)(int16, void*);
typedef bool (*get_token_callback)(int16, void*);
class BTokenSpace : public BLocker {
public:
BTokenSpace();
~BTokenSpace();
int32 NewToken(int16 type, void* object,
new_token_callback callback = NULL);
bool RemoveToken(int32 token, remove_token_callback callback = NULL);
bool CheckToken(int32 token, int16 type) const;
status_t GetToken(int32 token, int16 type, void** object,
get_token_callback callback = NULL) const;
status_t GetList(int32*& tokens, int32& count) const;
// Possible expansion
// void Dump(BDataIO&, bool) const;
// int32 NewToken(void*, BDirectMessageTarget*, void (*)(short, void*));
// bool SetTokenTarget(uint32, BDirectMessageTarget*);
// BDirectMessageTarget* TokenTarget(uint32 token, int16 type);
private:
struct TTokenInfo {
int16 type;
void* object;
};
typedef std::map<int32, TTokenInfo> TTokenMap;
TTokenMap fTokenMap;
std::stack<int32> fTokenBin;
int32 fTokenCount;
};
// Possible expansion
//_delete_tokens_();
//_init_tokens_();
//get_handler_token(short, void*);
//get_token_list(long, long*);
//new_handler_token(short, void*);
//remove_handler_token(short, void*);
extern _IMPEXP_BE BTokenSpace gDefaultTokens;
} // namespace BPrivate
#endif // _TOKEN_SPACE_H
#include <../private/app/TokenSpace.h>

View File

@ -1,152 +1 @@
/* $Xorg: region.h,v 1.4 2001/02/09 02:03:40 xorgcvs Exp $ */
/************************************************************************
Copyright 1987, 1998 The Open Group
Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
************************************************************************/
#ifndef __REGION_SUPPORT_H
#define __REGION_SUPPORT_H
#include <Region.h>
class BRegion::Support {
public:
static int XUnionRegion(const BRegion* reg1,
const BRegion* reg2, BRegion* newReg);
static int XIntersectRegion(const BRegion* reg1,
const BRegion* reg2, BRegion* newReg);
static int XSubtractRegion(const BRegion* regM,
const BRegion* regS, BRegion* regD);
static int XXorRegion(const BRegion* sra,
const BRegion* srb, BRegion* dr);
static int XPointInRegion(const BRegion* region,
int x, int y);
enum {
RectangleOut = 0,
RectanglePart = 1,
RectangleIn = 2
};
static int XRectInRegion(const BRegion* region,
const clipping_rect& rect);
private:
static BRegion* CreateRegion();
static void DestroyRegion(BRegion* r);
static void XOffsetRegion(BRegion* pRegion, int x, int y);
static void miSetExtents(BRegion* pReg);
static int miIntersectO(BRegion* pReg,
clipping_rect* r1, clipping_rect* r1End,
clipping_rect* r2, clipping_rect* r2End,
int top, int bottom);
static void miRegionCopy(BRegion* dstrgn, const BRegion* rgn);
static int miCoalesce(BRegion* pReg,
int prevStart, int curStart);
static int miUnionNonO(BRegion* pReg, clipping_rect* r,
clipping_rect* rEnd, int top, int bottom);
static int miUnionO(BRegion* pReg,
clipping_rect* r1, clipping_rect* r1End,
clipping_rect* r2, clipping_rect* r2End,
int top, int bottom);
static int miSubtractO(BRegion* pReg,
clipping_rect* r1, clipping_rect* r1End,
clipping_rect* r2, clipping_rect* r2End,
int top, int bottom);
static int miSubtractNonO1(BRegion* pReg,
clipping_rect* r, clipping_rect* rEnd,
int top, int bottom);
typedef int (*overlapProcp)(
BRegion* pReg,
clipping_rect* r1,
clipping_rect* r1End,
register clipping_rect* r2,
clipping_rect* r2End,
int top,
int bottom);
typedef int (*nonOverlapProcp)(
BRegion* pReg,
clipping_rect* r,
clipping_rect* rEnd,
int top,
int bottom);
static void miRegionOp(BRegion* newReg,
const BRegion* reg1, const BRegion* reg2,
int (*overlapFunc)(
register BRegion* pReg,
register clipping_rect* r1,
clipping_rect* r1End,
register clipping_rect* r2,
clipping_rect* r2End,
int top,
int bottom),
int (*nonOverlap1Func)(
register BRegion* pReg,
register clipping_rect* r,
clipping_rect* rEnd,
register int top,
register int bottom),
int (*nonOverlap2Func)(
register BRegion* pReg,
register clipping_rect* r,
clipping_rect* rEnd,
register int top,
register int bottom));
};
#endif // __REGION_SUPPORT_H
#include <../private/interface/RegionSupport.h>

View File

@ -1,172 +1 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2004, Haiku, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: clipping.h
// Author: Stefano Ceccherini (burton666@libero.it)
// Description: Helper methods to manipulate clipping_rects
//------------------------------------------------------------------------------
#ifndef __CLIPPING_H
#define __CLIPPING_H
#include <Region.h>
#include <SupportDefs.h>
/* Some methods to manipulate clipping_rects.
basically you can do almost everything you do with
BRects, just that clipping_rects can only have integer
coordinates (a thing that makes these perfect for drawing
calculations).
*/
// Returns the union of the given rects.
static inline clipping_rect
union_rect(const clipping_rect &r1, const clipping_rect &r2)
{
clipping_rect rect;
rect.left = min_c(r1.left, r2.left);
rect.top = min_c(r1.top, r2.top);
rect.right = max_c(r1.right, r2.right);
rect.bottom = max_c(r1.bottom, r2.bottom);
return rect;
}
// Returns the intersection of the given rects.
// The caller should check if the returned rect is valid. If it isn't valid,
// then the two rectangles don't intersect.
static inline clipping_rect
sect_rect(const clipping_rect &r1, const clipping_rect &r2)
{
clipping_rect rect;
rect.left = max_c(r1.left, r2.left);
rect.top = max_c(r1.top, r2.top);
rect.right = min_c(r1.right, r2.right);
rect.bottom = min_c(r1.bottom, r2.bottom);
return rect;
}
// Adds the given offsets to the given rect.
static inline void
offset_rect(clipping_rect &rect, int32 x, int32 y)
{
rect.left += x;
rect.top += y;
rect.right += x;
rect.bottom += y;
}
// Converts the given clipping_rect to a BRect
static inline BRect
to_BRect(const clipping_rect &rect)
{
return BRect((float)rect.left, (float)rect.top, (float)rect.right, (float)rect.bottom);
}
// Converts the given BRect to a clipping_rect.
static inline clipping_rect
to_clipping_rect(const BRect &rect)
{
clipping_rect clipRect;
clipRect.left = (int32)floor(rect.left);
clipRect.top = (int32)floor(rect.top);
clipRect.right = (int32)ceil(rect.right);
clipRect.bottom = (int32)ceil(rect.bottom);
return clipRect;
}
// Checks if the given point lies in the given rect's area
static inline bool
point_in(const clipping_rect &rect, int32 px, int32 py)
{
if (px >= rect.left && px <= rect.right
&& py >= rect.top && py <= rect.bottom)
return true;
return false;
}
// Same as above, but it accepts a BPoint parameter
static inline bool
point_in(const clipping_rect &rect, const BPoint &pt)
{
if (pt.x >= rect.left && pt.x <= rect.right
&& pt.y >= rect.top && pt.y <= rect.bottom)
return true;
return false;
}
// Checks if the rect is valid
static inline bool
valid_rect(const clipping_rect &rect)
{
if (rect.left <= rect.right && rect.top <= rect.bottom)
return true;
return false;
}
// Checks if the two rects intersect.
static inline bool
rects_intersect(const clipping_rect &rectA, const clipping_rect &rectB)
{
// We behave like BRect::Intersects() does:
// we return false if one of the two rects is not valid
if (!valid_rect(rectA) || !valid_rect(rectB))
return false;
// TODO: Is there a better algorithm ?
// the one we used is faster than
// ' return valid_rect(sect_rect(rectA, rectB)); ', though.
return !(rectA.left > rectB.right || rectA.top > rectB.bottom
|| rectA.right < rectB.left || rectA.bottom < rectB.top);
}
// Returns the width of the given rect.
static inline int32
rect_width(const clipping_rect &rect)
{
return rect.right - rect.left;
}
// Returns the height of the given rect.
static inline int32
rect_height(const clipping_rect &rect)
{
return rect.bottom - rect.top;
}
#endif // __CLIPPING_H
#include <../private/interface/clipping.h>

View File

@ -1,181 +1 @@
/*
* Copyright 2004-2010, Haiku, Inc.
* Distributed under the terms of the MIT License.
*/
#ifndef _UTF8_FUNCTIONS_H
#define _UTF8_FUNCTIONS_H
#include <SupportDefs.h>
static inline bool
IsInsideGlyph(uchar ch)
{
return (ch & 0xc0) == 0x80;
}
static inline uint32
UTF8NextCharLenUnsafe(const char *text)
{
const char *ptr = text;
do {
ptr++;
} while (IsInsideGlyph(*ptr));
return ptr - text;
}
static inline uint32
UTF8NextCharLen(const char *text)
{
if (text == NULL || *text == 0)
return 0;
return UTF8NextCharLenUnsafe(text);
}
static inline uint32
UTF8PreviousCharLen(const char *text, const char *limit)
{
const char *ptr = text;
if (ptr == NULL || limit == NULL)
return 0;
do {
if (ptr == limit)
break;
ptr--;
} while (IsInsideGlyph(*ptr));
return text - ptr;
}
/*! UTF8CountBytes gets the length (in bytes) of a UTF8 string. Up to
numChars characters are read. If numChars is a negative value it is ignored
and the string is read up to the terminating 0.
*/
static inline uint32
UTF8CountBytes(const char *bytes, int32 numChars)
{
if (bytes == NULL)
return 0;
if (numChars < 0)
numChars = INT_MAX;
const char *base = bytes;
while (bytes[0] != '\0') {
if ((bytes[0] & 0xc0) != 0x80) {
if (--numChars < 0)
break;
}
bytes++;
}
return bytes - base;
}
/*! UTF8CountChars gets the length (in characters) of a UTF8 string. Up to
numBytes bytes are read. If numBytes is a negative value it is ignored
and the string is read up to the terminating 0.
*/
static inline uint32
UTF8CountChars(const char *bytes, int32 numBytes)
{
if (bytes == NULL)
return 0;
uint32 length = 0;
const char *last;
if (numBytes < 0)
last = (const char *)SIZE_MAX;
else
last = bytes + numBytes - 1;
while (bytes[0] && bytes <= last) {
if ((bytes++[0] & 0xc0) != 0x80)
length++;
}
return length;
}
/*! UTF8ToCharCode converts the input that includes potential multibyte chars
to UTF-32 char codes that can be used by FreeType. The string pointer is
then advanced to the next character in the string. In case the terminating
0 is reached, the string pointer is not advanced anymore and nulls are
returned. This makes it safe to overruns and enables streamed processing
of UTF8 strings.
*/
static inline uint32
UTF8ToCharCode(const char **bytes)
{
#define UTF8_SUBSTITUTE_CHARACTER 0xfffd
uint32 result;
if (((*bytes)[0] & 0x80) == 0) {
// a single byte character
result = (*bytes)[0];
if (result != '\0') {
// do not advance beyond the terminating '\0'
(*bytes)++;
}
return result;
}
if (((*bytes)[0] & 0xc0) == 0x80) {
// not a proper multibyte start
(*bytes)++;
return UTF8_SUBSTITUTE_CHARACTER;
}
// start of a multibyte character
uint8 mask = 0x80;
result = (uint32)((*bytes)[0] & 0xff);
(*bytes)++;
while (result & mask) {
if (mask == 0x02) {
// seven byte char - invalid
return UTF8_SUBSTITUTE_CHARACTER;
}
result &= ~mask;
mask >>= 1;
}
while (((*bytes)[0] & 0xc0) == 0x80) {
result <<= 6;
result += (*bytes)[0] & 0x3f;
(*bytes)++;
mask <<= 1;
if (mask == 0x40)
return result;
}
if (mask == 0x40)
return result;
if ((*bytes)[0] == '\0') {
// string terminated within multibyte char
return 0x00;
}
// not enough bytes in multibyte char
return UTF8_SUBSTITUTE_CHARACTER;
#undef UTF8_SUBSTITUTE_CHARACTER
}
#endif // _UTF8_FUNCTIONS_H
#include <../private/interface/utf8_functions.h>

View File

@ -0,0 +1 @@
#include <../private/kernel/util/KMessage.h>

View File

@ -1,220 +1 @@
/*
* Copyright 2001-2007, Ingo Weinhold, bonefish@users.sf.net. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#ifndef _AUTO_DELETER_H
#define _AUTO_DELETER_H
/*! Scope-based automatic deletion of objects/arrays.
ObjectDeleter - deletes an object
ArrayDeleter - deletes an array
MemoryDeleter - free()s malloc()ed memory
CObjectDeleter - calls an arbitrary specified destructor function
*/
#include <stdlib.h>
namespace BPrivate {
// AutoDeleter
template<typename C, typename DeleteFunc>
class AutoDeleter {
public:
inline AutoDeleter()
: fObject(NULL)
{
}
inline AutoDeleter(C *object)
: fObject(object)
{
}
inline ~AutoDeleter()
{
fDelete(fObject);
}
inline void SetTo(C *object)
{
if (object != fObject) {
fDelete(fObject);
fObject = object;
}
}
inline void Unset()
{
SetTo(NULL);
}
inline void Delete()
{
SetTo(NULL);
}
inline C *Get() const
{
return fObject;
}
inline C *Detach()
{
C *object = fObject;
fObject = NULL;
return object;
}
protected:
C *fObject;
DeleteFunc fDelete;
};
// ObjectDeleter
template<typename C>
struct ObjectDelete
{
inline void operator()(C *object)
{
delete object;
}
};
template<typename C>
struct ObjectDeleter : AutoDeleter<C, ObjectDelete<C> >
{
ObjectDeleter() : AutoDeleter<C, ObjectDelete<C> >() {}
ObjectDeleter(C *object) : AutoDeleter<C, ObjectDelete<C> >(object) {}
};
// ArrayDeleter
template<typename C>
struct ArrayDelete
{
inline void operator()(C *array)
{
delete[] array;
}
};
template<typename C>
struct ArrayDeleter : AutoDeleter<C, ArrayDelete<C> >
{
ArrayDeleter() : AutoDeleter<C, ArrayDelete<C> >() {}
ArrayDeleter(C *array) : AutoDeleter<C, ArrayDelete<C> >(array) {}
};
// MemoryDeleter
struct MemoryDelete
{
inline void operator()(void *memory)
{
free(memory);
}
};
struct MemoryDeleter : AutoDeleter<void, MemoryDelete >
{
MemoryDeleter() : AutoDeleter<void, MemoryDelete >() {}
MemoryDeleter(void *memory) : AutoDeleter<void, MemoryDelete >(memory) {}
};
// CObjectDeleter
template<typename Type, typename DestructorReturnType>
struct CObjectDelete
{
inline void operator()(Type *object)
{
if (fDestructor != NULL && object != NULL)
fDestructor(object);
}
template<typename Destructor>
inline void operator=(Destructor destructor)
{
fDestructor = destructor;
}
private:
DestructorReturnType (*fDestructor)(Type*);
};
template<typename Type, typename DestructorReturnType = void>
struct CObjectDeleter
: AutoDeleter<Type, CObjectDelete<Type, DestructorReturnType> >
{
typedef AutoDeleter<Type, CObjectDelete<Type, DestructorReturnType> > Base;
template<typename Destructor>
CObjectDeleter(Destructor destructor) : Base()
{
Base::fDelete = destructor;
}
template<typename Destructor>
CObjectDeleter(Type *object, Destructor destructor) : Base(object)
{
Base::fDelete = destructor;
}
};
// MethodDeleter
template<typename Type, typename DestructorReturnType>
struct MethodDelete
{
inline void operator()(Type *object)
{
if (fDestructor && object != NULL)
(object->*fDestructor)();
}
template<typename Destructor>
inline void operator=(Destructor destructor)
{
fDestructor = destructor;
}
private:
DestructorReturnType (Type::*fDestructor)();
};
template<typename Type, typename DestructorReturnType = void>
struct MethodDeleter
: AutoDeleter<Type, MethodDelete<Type, DestructorReturnType> >
{
typedef AutoDeleter<Type, MethodDelete<Type, DestructorReturnType> > Base;
template<typename Destructor>
MethodDeleter(Destructor destructor) : Base()
{
Base::fDelete = destructor;
}
template<typename Destructor>
MethodDeleter(Type *object, Destructor destructor) : Base(object)
{
Base::fDelete = destructor;
}
};
} // namespace BPrivate
using BPrivate::ObjectDeleter;
using BPrivate::ArrayDeleter;
using BPrivate::MemoryDeleter;
using BPrivate::CObjectDeleter;
using BPrivate::MethodDeleter;
#endif // _AUTO_DELETER_H
#include <../private/shared/AutoDeleter.h>

View File

@ -0,0 +1 @@
#include <../private/shared/AutoLocker.h>

View File

@ -1,61 +1 @@
/*
* Copyright 2004-2010, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Jérôme Duval
* Axel Dörfler, axeld@pinc-software.de.
*/
#ifndef _KEYMAP_H
#define _KEYMAP_H
#include <DataIO.h>
#include <InterfaceDefs.h>
class BKeymap {
public:
BKeymap();
virtual ~BKeymap();
status_t SetTo(const char* path);
status_t SetTo(BDataIO& stream);
status_t SetToCurrent();
status_t SetToDefault();
void Unset();
bool IsModifierKey(uint32 keyCode) const;
uint32 Modifier(uint32 keyCode) const;
uint32 KeyForModifier(uint32 modifier) const;
uint8 ActiveDeadKey(uint32 keyCode,
uint32 modifiers) const;
uint8 DeadKey(uint32 keyCode, uint32 modifiers,
bool* _isEnabled) const;
bool IsDeadSecondKey(uint32 keyCode,
uint32 modifiers,
uint8 activeDeadKey) const;
void GetChars(uint32 keyCode, uint32 modifiers,
uint8 activeDeadKey, char** chars,
int32* numBytes) const;
const key_map& Map() const { return fKeys; }
bool operator==(const BKeymap& other) const;
bool operator!=(const BKeymap& other) const;
BKeymap& operator=(const BKeymap& other);
protected:
int32 Offset(uint32 keyCode, uint32 modifiers,
uint32* _table = NULL) const;
uint8 DeadKeyIndex(int32 offset) const;
protected:
char* fChars;
key_map fKeys;
uint32 fCharsSize;
};
#endif // KEYMAP_H
#include <../private/shared/Keymap.h>

View File

@ -1,100 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: ObjectLocker.h
// Author(s): Erik Jaesler (erik@cgsoftware.com)
// Description: A templatized version of BAutolock. Client class needs to
// supply:
// bool Lock() -- returns whether lock succeeded
// void Unlock() -- unlocks the class
//------------------------------------------------------------------------------
#ifndef OBJECTLOCKER_H
#define OBJECTLOCKER_H
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
namespace BPrivate {
template<class T>
class BObjectLocker
{
public:
inline BObjectLocker(T* looper);
inline BObjectLocker(T& locker);
inline ~BObjectLocker();
inline bool IsLocked(void);
private:
T* fLockClient;
bool fIsLocked;
};
template<class T>
BObjectLocker<T>::BObjectLocker(T* client)
: fLockClient(client), fIsLocked(client->Lock())
{
}
template<class T>
BObjectLocker<T>::BObjectLocker(T& client)
: fLockClient(&client), fIsLocked(client.Lock())
{
}
template<class T>
BObjectLocker<T>::~BObjectLocker()
{
if (fIsLocked)
{
fLockClient->Unlock();
}
}
template<class T>
bool BObjectLocker<T>::IsLocked(void)
{
return fIsLocked;
}
} // namespace BPrivate
#endif //OBJECTLOCKER_H
/*
* $Log $
*
* $Id $
*
*/

View File

@ -1,94 +1 @@
/*
* Copyright 2002-2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#ifndef _ELF_H
#define _ELF_H
#include <SupportDefs.h>
// types
typedef uint32 Elf32_Addr;
typedef uint32 Elf32_Off;
typedef uint16 Elf32_Half;
typedef int32 Elf32_Sword;
typedef uint32 Elf32_Word;
typedef uint32 Elf32_Xword;
typedef int32 Elf32_Sxword;
typedef uint64 Elf64_Addr;
typedef uint64 Elf64_Off;
typedef uint16 Elf64_Half;
typedef int32 Elf64_Sword;
typedef uint32 Elf64_Word;
typedef uint64 Elf64_Xword;
typedef int64 Elf64_Sxword;
// e_ident indices
#define EI_MAG0 0
#define EI_MAG1 1
#define EI_MAG2 2
#define EI_MAG3 3
#define EI_CLASS 4
#define EI_DATA 5
#define EI_VERSION 6
#define EI_PAD 7
#define EI_NIDENT 16
// e_ident EI_VERSION values
#define EV_NONE 0
#define EV_CURRENT 1
// e_ident EI_CLASS and EI_DATA values
#define ELFCLASSNONE 0
#define ELFCLASS32 1
#define ELFCLASS64 2
#define ELFDATANONE 0
#define ELFDATA2LSB 1
#define ELFDATA2MSB 2
// p_type
#define PT_NULL 0
#define PT_LOAD 1
#define PT_DYNAMIC 2
#define PT_INTERP 3
#define PT_NOTE 4
#define PT_SHLIB 5
#define PT_PHDIR 6
#define PT_LOPROC 0x70000000
#define PT_HIPROC 0x7fffffff
// sh_type values
#define SHT_NULL 0
#define SHT_PROGBITS 1
#define SHT_SYMTAB 2
#define SHT_STRTAB 3
#define SHT_RELA 4
#define SHT_HASH 5
#define SHT_DYNAMIC 6
#define SHT_NOTE 7
#define SHT_NOBITS 8
#define SHT_REL 9
#define SHT_SHLIB 10
#define SHT_DYNSYM 11
#define SHT_LOPROC 0x70000000
#define SHT_HIPROC 0x7fffffff
#define SHT_LOUSER 0x80000000
#define SHT_HIUSER 0xffffffff
// 32 bit definitions
#undef _ELFX_BITS
#define _ELFX_BITS 32
#include <ElfX.h>
// 64 bit definitions
#undef _ELFX_BITS
#define _ELFX_BITS 64
#include <ElfX.h>
#undef _ELFX_BITS
#endif // _ELF_H
#include <../private/storage/Elf.h>

View File

@ -1,68 +1 @@
/*
* Copyright 2002-2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
// No header guard: The file is included twice by <Elf.h> and must not be
// included elsewhere. The _ELFX_BITS macro must be define before inclusion.
#undef ElfX
#if _ELFX_BITS == 32
# define ElfX(x) Elf32_##x
#elif _ELFX_BITS == 64
# define ElfX(x) Elf64_##x
#endif
// object file header
typedef struct {
unsigned char e_ident[EI_NIDENT];
ElfX(Half) e_type;
ElfX(Half) e_machine;
ElfX(Word) e_version;
ElfX(Addr) e_entry;
ElfX(Off) e_phoff;
ElfX(Off) e_shoff;
ElfX(Word) e_flags;
ElfX(Half) e_ehsize;
ElfX(Half) e_phentsize;
ElfX(Half) e_phnum;
ElfX(Half) e_shentsize;
ElfX(Half) e_shnum;
ElfX(Half) e_shstrndx;
} ElfX(Ehdr);
// program header
typedef struct {
ElfX(Word) p_type;
#if _ELFX_BITS == 64
ElfX(Word) p_flags;
#endif
ElfX(Off) p_offset;
ElfX(Addr) p_vaddr;
ElfX(Addr) p_paddr;
ElfX(Xword) p_filesz;
ElfX(Xword) p_memsz;
#if _ELFX_BITS == 32
ElfX(Word) p_flags;
#endif
ElfX(Xword) p_align;
} ElfX(Phdr);
// section header
typedef struct {
ElfX(Word) sh_name;
ElfX(Word) sh_type;
ElfX(Xword) sh_flags;
ElfX(Addr) sh_addr;
ElfX(Off) sh_offset;
ElfX(Xword) sh_size;
ElfX(Word) sh_link;
ElfX(Word) sh_info;
ElfX(Xword) sh_addralign;
ElfX(Xword) sh_entsize;
} ElfX(Shdr);
#undef ElfX
#include <../private/storage/ElfX.h>

View File

@ -1,115 +1 @@
// Exception
#ifndef _EXCEPTION_H
#define _EXCEPTION_H
#include <stdarg.h>
#include <stdio.h>
#include <String.h>
namespace BPrivate {
namespace Storage {
class Exception {
public:
// constructor
Exception()
: fError(B_OK),
fDescription()
{
}
// constructor
Exception(BString description)
: fError(B_OK),
fDescription(description)
{
}
// constructor
Exception(const char* format,...)
: fError(B_OK),
fDescription()
{
va_list args;
va_start(args, format);
SetTo(B_OK, format, args);
va_end(args);
}
// constructor
Exception(status_t error)
: fError(error),
fDescription()
{
}
// constructor
Exception(status_t error, BString description)
: fError(error),
fDescription(description)
{
}
// constructor
Exception(status_t error, const char* format,...)
: fError(error),
fDescription()
{
va_list args;
va_start(args, format);
SetTo(error, format, args);
va_end(args);
}
// copy constructor
Exception(const Exception& exception)
: fError(exception.fError),
fDescription(exception.fDescription)
{
}
// destructor
~Exception()
{
}
// SetTo
void SetTo(status_t error, BString description)
{
fError = error;
fDescription.SetTo(description);
}
// SetTo
void SetTo(status_t error, const char* format, va_list arg)
{
char buffer[2048];
vsprintf(buffer, format, arg);
SetTo(error, BString(buffer));
}
// GetError
status_t Error() const
{
return fError;
}
// GetDescription
const char* Description() const
{
return fDescription.String();
}
private:
status_t fError;
BString fDescription;
};
}; // namespace Storage
}; // namespace BPrivate
#endif // _EXCEPTION_H
#include <../private/storage/Exception.h>

View File

@ -1,46 +1 @@
/*
* Copyright 2009-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#ifndef _FILE_IO_H
#define _FILE_IO_H
#include <stdio.h>
#include <DataIO.h>
class BFileIO : public BPositionIO {
public:
BFileIO(FILE* file,
bool takeOverOwnership = false);
virtual ~BFileIO();
virtual ssize_t Read(void *buffer, size_t size);
virtual ssize_t Write(const void *buffer, size_t size);
virtual ssize_t ReadAt(off_t position, void *buffer,
size_t size);
virtual ssize_t WriteAt(off_t position, const void *buffer,
size_t size);
virtual off_t Seek(off_t position, uint32 seekMode);
virtual off_t Position() const;
virtual status_t SetSize(off_t size);
virtual status_t GetSize(off_t* size) const;
private:
BFileIO(const BFileIO& other);
BFileIO& operator=(const BFileIO& other);
off_t _Seek(off_t position, uint32 seekMode) const;
private:
FILE* fFile;
bool fOwnsFile;
};
#endif // _FILE_IO_H
#include <../private/storage/FileIO.h>

View File

@ -1,21 +1 @@
/*
** Copyright 2004, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
** Distributed under the terms of the OpenBeOS License.
*/
#ifndef _MIME_TYPES_H
#define _MIME_TYPES_H
#include <Mime.h>
// Additional MIME types that are not defined in Mime.h but are
// standard values. We should move them into a public space some
// day.
#define B_DIRECTORY_MIME_TYPE "application/x-vnd.Be-directory"
#define B_VOLUME_MIME_TYPE "application/x-vnd.Be-volume"
#define B_SYMLINK_MIME_TYPE "application/x-vnd.Be-symlink"
#define B_ROOT_MIME_TYPE "application/x-vnd.Be-root"
#endif /* _MIME_TYPES_H */
#include <../private/storage/MimeTypes.h>

View File

@ -1,67 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file OffsetFile.h
OffsetFile interface declaration.
*/
#ifndef _OFFSET_FILE_H
#define _OFFSET_FILE_H
#include <DataIO.h>
#include <File.h>
namespace BPrivate {
namespace Storage {
/*!
\class OffsetFile
\brief Provides access to a file skipping a certain amount of bytes at
the beginning.
This class implements the BPositionIO interface to provide access to the
data of a file past a certain offset. This is very handy e.g. for dealing
with resources, as they always reside at the end of a file, but may start
at arbitrary offsets.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class OffsetFile : public BPositionIO {
public:
OffsetFile();
OffsetFile(BFile *file, off_t offset);
virtual ~OffsetFile();
status_t SetTo(BFile *file, off_t offset);
void Unset();
status_t InitCheck() const;
BFile *File() const;
ssize_t ReadAt(off_t pos, void *buffer, size_t size);
ssize_t WriteAt(off_t pos, const void *buffer,
size_t size);
off_t Seek(off_t position, uint32 seekMode);
off_t Position() const;
status_t SetSize(off_t size);
status_t GetSize(off_t *size) const;
off_t Offset() const;
private:
BFile* fFile;
off_t fOffset;
off_t fCurrentPosition;
};
}; // namespace Storage
}; // namespace BPrivate
#endif // _OFFSET_FILE_H
#include <../private/storage/OffsetFile.h>

View File

@ -1,48 +1 @@
// Pef.h
#ifndef _PEF_H
#define _PEF_H
#include <SupportDefs.h>
typedef char PefOSType[4];
// container header
struct PEFContainerHeader {
PefOSType tag1;
PefOSType tag2;
PefOSType architecture;
uint32 formatVersion;
uint32 dateTimeStamp;
uint32 oldDefVersion;
uint32 oldImpVersion;
uint32 currentVersion;
uint16 sectionCount;
uint16 instSectionCount;
uint32 reservedA;
};
const char kPEFFileMagic1[4] = { 'J', 'o', 'y', '!' };
const char kPEFFileMagic2[4] = { 'p', 'e', 'f', 'f' };
const char kPEFArchitecturePPC[4] = { 'p', 'w', 'p', 'c' };
const char kPEFContainerHeaderSize = 40;
// section header
struct PEFSectionHeader {
int32 nameOffset;
uint32 defaultAddress;
uint32 totalSize;
uint32 unpackedSize;
uint32 packedSize;
uint32 containerOffset;
uint8 sectionKind;
uint8 shareKind;
uint8 alignment;
uint8 reservedA;
};
const uint32 kPEFSectionHeaderSize = 28;
#endif // _PEF_H
#include <../private/storage/Pef.h>

View File

@ -1,162 +1 @@
/*
* Copyright 2002-2009, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#ifndef _RESOURCE_FILE_H
#define _RESOURCE_FILE_H
/*!
\file ResourceFile.h
ResourceFile interface declaration.
*/
#include <ByteOrder.h>
#include "OffsetFile.h"
struct resource_info;
struct PEFContainerHeader;
namespace BPrivate {
namespace Storage {
class Exception;
struct MemArea;
class ResourceItem;
struct resource_parse_info;
class ResourcesContainer;
/*!
\class ResourceFile
\brief Represents a file capable of containing resources.
This class provides access to the resources of a file.
Basically a ResourceFile object can be set to a file, load infos for the
resources without loading their data (InitContainer()), read the data of
one (ReadResource()) or all resources (ReadResources()) and write all
resources to the file (WriteResources()).
Note, that the object does only provide the I/O functionality, it does
not store any information about the resources -- this is done via a
ResourcesContainer. We gain flexibility using this approach, since e.g.
a certain resource may be represented by more than one ResourceItem and
we can have as many ResourcesContainers for the resources as we like.
In particular it is nice, that at any time we can write an arbitrary set
of resources to the file.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class ResourceFile {
public:
ResourceFile();
virtual ~ResourceFile();
status_t SetTo(BFile* file, bool clobber = false);
void Unset();
status_t InitCheck() const;
status_t InitContainer(ResourcesContainer& container);
status_t ReadResource(ResourceItem& resource,
bool force = false);
status_t ReadResources(ResourcesContainer& container,
bool force = false);
status_t WriteResources(ResourcesContainer& container);
private:
void _InitFile(BFile& file, bool clobber);
void _InitELFFile(BFile& file);
template<typename ElfHeader, typename ElfProgramHeader,
typename ElfSectionHeader>
void _InitELFXFile(BFile& file, uint64 fileSize);
void _InitPEFFile(BFile& file,
const PEFContainerHeader& pefHeader);
void _ReadHeader(resource_parse_info& parseInfo);
void _ReadIndex(resource_parse_info& parseInfo);
bool _ReadIndexEntry(resource_parse_info& parseInfo,
int32 index, uint32 tableOffset,
bool peekAhead);
void _ReadInfoTable(resource_parse_info& parseInfo);
bool _ReadInfoTableEnd(const void* data,
int32 dataSize);
const void* _ReadResourceInfo(
resource_parse_info& parseInfo,
const MemArea& area,
const resource_info* info, type_code type,
bool* readIndices);
status_t _WriteResources(ResourcesContainer& container);
status_t _MakeEmptyResourceFile();
inline int16 _GetInt(int16 value) const;
inline uint16 _GetInt(uint16 value) const;
inline int32 _GetInt(int32 value) const;
inline uint32 _GetInt(uint32 value) const;
inline int64 _GetInt(int64 value) const;
inline uint64 _GetInt(uint64 value) const;
private:
OffsetFile fFile;
uint32 fFileType;
bool fHostEndianess;
bool fEmptyResources;
};
inline int16
ResourceFile::_GetInt(int16 value) const
{
return fHostEndianess ? value : (int16)B_SWAP_INT16((uint16)value);
}
inline uint16
ResourceFile::_GetInt(uint16 value) const
{
return fHostEndianess ? value : B_SWAP_INT16(value);
}
inline int32
ResourceFile::_GetInt(int32 value) const
{
return fHostEndianess ? value : (int32)B_SWAP_INT32((uint32)value);
}
inline uint32
ResourceFile::_GetInt(uint32 value) const
{
return fHostEndianess ? value : B_SWAP_INT32(value);
}
inline int64
ResourceFile::_GetInt(int64 value) const
{
return fHostEndianess ? value : (int64)B_SWAP_INT64((uint64)value);
}
inline uint64
ResourceFile::_GetInt(uint64 value) const
{
return fHostEndianess ? value : B_SWAP_INT64(value);
}
}; // namespace Storage
}; // namespace BPrivate
#endif // _RESOURCE_FILE_H
#include <../private/storage/ResourceFile.h>

View File

@ -1,91 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file ResourcesItem.h
ResourceItem interface declaration.
*/
#ifndef _RESOURCE_ITEM_H
#define _RESOURCE_ITEM_H
#include <DataIO.h>
#include <String.h>
namespace BPrivate {
namespace Storage {
/*!
\class ResourceItem
\brief Represents a resource loaded into memory.
This class represents a resource completely or partially loaded into
memory. The minimal information stored in the object should be its
type, ID and name and the size of its data. If the data are not loaded
then additionally the offset (into a resource file) should be valid.
As soon as the data are loaded as well, the offset is more or less
meaningless.
Creating a new resource can be done by calling SetIdentity() after the
default construction. The object then represents a resource with the
specified type, ID and name and with empty data. Data can arbitrarily
be read and written using the methods the super class BMallocIO provides.
The memory for the resource data is owned by the ResourceItem object and
freed on destruction.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class ResourceItem : public BMallocIO {
public:
ResourceItem();
virtual ~ResourceItem();
virtual ssize_t WriteAt(off_t pos, const void *buffer, size_t size);
virtual status_t SetSize(off_t size);
void SetLocation(int32 offset, size_t initialSize);
void SetIdentity(type_code type, int32 id, const char *name);
void SetOffset(int32 offset);
int32 Offset() const;
size_t InitialSize() const;
size_t DataSize() const;
void SetType(type_code type);
type_code Type() const;
void SetID(int32 id);
int32 ID() const;
void SetName(const char *name);
const char *Name() const;
void *Data() const;
void SetLoaded(bool loaded);
bool IsLoaded() const;
void SetModified(bool modified);
bool IsModified() const;
private:
int32 fOffset;
size_t fInitialSize;
type_code fType;
int32 fID;
BString fName;
bool fIsLoaded;
bool fIsModified;
};
}; // namespace Storage
}; // namespace BPrivate
#endif // _RESOURCE_ITEM_H
#include <../private/storage/ResourceItem.h>

View File

@ -1,79 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file ResourcesContainer.h
ResourcesContainer interface declaration.
*/
#ifndef _RESOURCES_CONTAINER_H
#define _RESOURCES_CONTAINER_H
#include <List.h>
namespace BPrivate {
namespace Storage {
class ResourceItem;
/*!
\class ResourcesContainer
\brief Represents a collection of resources.
This class can be used to manage a collection of resources represented
by ResourceItem's. Usually it does never contain two resources with the
same type \em and ID, since AddResource() replaces an old item with the
new one, unless explicitly told not to do so. This should only be done
by ResourceFile, when type and ID of the items are not yet known.
Asside from the basic vector features like Add/RemoveResource()/
ResourceAt() and MakeEmpty() a bunch of IndexOf() methods are provided
and AssimilateResources() which incorporates all resources of another
container into this one (replacing old resources, if necessary), emptying
the other one.
The ResourceItem's in a container are deleted on destruction, unless
removed before via RemoveResource(). MakeEmpty() deletes the items as
well.
\author <a href='mailto:bonefish@users.sf.net'>Ingo Weinhold</a>
\version 0.0.0
*/
class ResourcesContainer {
public:
ResourcesContainer();
virtual ~ResourcesContainer();
bool AddResource(ResourceItem *item, int32 index = -1,
bool replace = true);
ResourceItem *RemoveResource(int32 index);
bool RemoveResource(ResourceItem *item);
void MakeEmpty();
void AssimilateResources(ResourcesContainer &container);
int32 IndexOf(ResourceItem *item) const;
int32 IndexOf(const void *data) const;
int32 IndexOf(type_code type, int32 id) const;
int32 IndexOf(type_code type, const char *name) const;
int32 IndexOfType(type_code type, int32 index) const;
ResourceItem *ResourceAt(int32 index) const;
int32 CountResources() const;
void SetModified(bool modified);
bool IsModified() const;
private:
BList fResources;
bool fIsModified;
};
}; // namespace Storage
}; // namespace BPrivate
#endif // _RESOURCES_CONTAINER_H
#include <../private/storage/ResourcesContainer.h>

View File

@ -1,107 +1 @@
// ResourcesDefs.h
#ifndef _DEF_RESOURCES_H
#define _DEF_RESOURCES_H
#include <SupportDefs.h>
// x86 resource file constants
const char kX86ResourceFileMagic[4] = { 'R', 'S', 0, 0 };
const uint32 kX86ResourcesOffset = 0x00000004;
// PPC resource file constants
const char kPPCResourceFileMagic[4] = { 'r', 'e', 's', 'f' };
const uint32 kPPCResourcesOffset = 0x00000028;
// ELF file related constants
const uint32 kELFMinResourceAlignment = 32;
// the unused data pattern
const uint32 kUnusedResourceDataPattern[3] = {
0xffffffff, 0x000003e9, 0x00000000
};
// the resources header
struct resources_header {
uint32 rh_resources_magic;
uint32 rh_resource_count;
uint32 rh_index_section_offset;
uint32 rh_admin_section_size;
uint32 rh_pad[13];
};
const uint32 kResourcesHeaderMagic = 0x444f1000;
const uint32 kResourceIndexSectionOffset = 0x00000044;
const uint32 kResourceIndexSectionAlignment = 0x00000600;
const uint32 kResourcesHeaderSize = 68;
// the header of the index section
struct resource_index_section_header {
uint32 rish_index_section_offset;
uint32 rish_index_section_size;
uint32 rish_unused_data1;
uint32 rish_unknown_section_offset;
uint32 rish_unknown_section_size;
uint32 rish_unused_data2[25];
uint32 rish_info_table_offset;
uint32 rish_info_table_size;
uint32 rish_unused_data3;
};
const uint32 kUnknownResourceSectionSize = 0x00000168;
const uint32 kResourceIndexSectionHeaderSize = 132;
// an entry of the index table
struct resource_index_entry {
uint32 rie_offset;
uint32 rie_size;
uint32 rie_pad;
};
const uint32 kResourceIndexEntrySize = 12;
// a resource info
struct resource_info {
int32 ri_id;
int32 ri_index;
uint16 ri_name_size;
char ri_name[1];
};
const uint32 kMinResourceInfoSize = 10;
// a resource info block
struct resource_info_block {
type_code rib_type;
resource_info rib_info[1];
};
const uint32 kMinResourceInfoBlockSize = 4 + kMinResourceInfoSize;
// the structure separating resource info blocks
struct resource_info_separator {
uint32 ris_value1;
uint32 ris_value2;
};
const uint32 kResourceInfoSeparatorSize = 8;
// the end of the info table
struct resource_info_table_end {
uint32 rite_check_sum;
uint32 rite_terminator;
};
const uint32 kResourceInfoTableEndSize = 8;
#endif // _DEF_RESOURCES_H
#include <../private/storage/ResourcesDefs.h>

View File

@ -1,146 +1 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file storage_support.h
Interface declarations for miscellaneous internal
Storage Kit support functions.
*/
#ifndef _STORAGE_SUPPORT_H
#define _STORAGE_SUPPORT_H
#include <dirent.h>
#include <string>
namespace BPrivate {
namespace Storage {
// For convenience:
struct LongDirEntry : dirent { char _buffer[B_FILE_NAME_LENGTH]; };
//! Returns whether the supplied path is absolute.
bool is_absolute_path(const char *path);
status_t parse_path(const char *fullPath, int &dirEnd, int &leafStart,
int &leafEnd);
status_t parse_path(const char *fullPath, char *dirPath, char *leaf);
//! splits a path name into directory path and leaf name
status_t split_path(const char *fullPath, char *&path, char *&leaf);
//! splits a path name into directory path and leaf name
status_t split_path(const char *fullPath, char **path, char **leaf);
//! Parses the first component of a path name.
status_t parse_first_path_component(const char *path, int32& length,
int32& nextComponent);
//! Parses the first component of a path name.
status_t parse_first_path_component(const char *path, char *&component,
int32& nextComponent);
//! Checks whether an entry name is a valid entry name.
status_t check_entry_name(const char *entry);
//! Checks whether a path name is a valid path name.
status_t check_path_name(const char *path);
/*! \brief Returns a copy of \c str in which all alphabetic characters
are lowercase.
Returns \c "(null)" if you're a bonehead and pass in a \c NULL pointer.
*/
std::string to_lower(const char *str);
/*! \brief Places a copy of \c str in \c result in which all alphabetic
characters are lowercase.
Returns \c "(null)" if you're a bonehead and pass in a \c NULL pointer.
*/
void to_lower(const char *str, std::string &result);
/*! \brief Copies \c str into \c result, converting any uppercase alphabetics
to lowercase.
\a str and \a result may point to the same string. \a result is
assumed to be as long as or longer than \a str.
*/
void to_lower(const char *str, char *result);
//! Converts \c str to lowercase.
void to_lower(char *str);
/*! \brief Escapes any whitespace or other special characters in the path
\a result must be large enough to accomodate the addition of
escape sequences to \a str. \a str and \a result may *NOT* point to
the same string.
Note that this function was designed for use with the registrar's
RecentEntries class, and may not create escapes exactly like you're
hoping. Please double check the code for the function to see if this
is the case.
*/
void escape_path(const char *str, char *result);
/*! \brief Escapes any whitespace or other special characters in the path
\a str must be large enough to accomodate the addition of
escape sequences.
*/
void escape_path(char *str);
/*! \brief Returns whether the supplied device ID refers to the root FS.
*/
bool device_is_root_device(dev_t device);
// FDCloser
class FDCloser {
public:
FDCloser(int fd)
: fFD(fd)
{
}
~FDCloser()
{
Close();
}
void SetTo(int fd)
{
Close();
fFD = fd;
}
// implemented in the source file to not expose syscalls to the unit tests
// which include this file too
void Close();
// void Close()
// {
// if (fFD >= 0)
// _kern_close(fFD);
// fFD = -1;
// }
int Detach()
{
int fd = fFD;
fFD = -1;
return fd;
}
private:
int fFD;
};
}; // namespace Storage
}; // namespace BPrivate
using BPrivate::Storage::FDCloser;
#endif // _STORAGE_SUPPORT_H
#include <../private/storage/storage_support.h>

View File

@ -1,6 +1,8 @@
SubDir HAIKU_TOP src build libbe app ;
UsePrivateBuildHeaders app shared ;
UsePrivateBuildHeaders app kernel shared ;
SEARCH_SOURCE += [ FDirName $(HAIKU_TOP) src kits app ] ;
USES_BE_API on <libbe_build>app_kit.o = true ;

View File

@ -1,5 +1,5 @@
/*
* Copyright 2005-2009, Haiku Inc. All rights reserved.
* Copyright 2005-2011, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
@ -598,9 +598,9 @@ BMessage::_PrintToStream(const char* indent) const
entry_ref ref;
BPrivate::entry_ref_unflatten(&ref, (char *)pointer, size);
printf("entry_ref(device=%d, directory=%" B_PRIdINO
", name=\"%s\", ", (int)ref.device, ref.directory,
ref.name);
printf("entry_ref(device=%d, directory=%lld"
", name=\"%s\", ", (int)ref.device,
(long long)ref.directory, ref.name);
BPath path(&ref);
printf("path=\"%s\")\n", path.Path());

View File

@ -1,748 +0,0 @@
/*
* Copyright 2005-2007, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Axel Dörfler, axeld@pinc-software.de
* Michael Lotz <mmlr@mlotz.ch>
*/
#include <MessageAdapter.h>
#include <MessagePrivate.h>
#include <MessageUtils.h>
#include <stdlib.h>
namespace BPrivate {
#define R5_MESSAGE_FLAG_VALID 0x01
#define R5_MESSAGE_FLAG_INCLUDE_TARGET 0x02
#define R5_MESSAGE_FLAG_INCLUDE_REPLY 0x04
#define R5_MESSAGE_FLAG_SCRIPT_MESSAGE 0x08
#define R5_FIELD_FLAG_VALID 0x01
#define R5_FIELD_FLAG_MINI_DATA 0x02
#define R5_FIELD_FLAG_FIXED_SIZE 0x04
#define R5_FIELD_FLAG_SINGLE_ITEM 0x08
enum {
SECTION_MESSAGE_HEADER = 'FOB2',
SECTION_OFFSET_TABLE = 'STof',
SECTION_TARGET_INFORMATION = 'ENwh',
SECTION_SINGLE_ITEM_DATA = 'SGDa',
SECTION_FIXED_SIZE_ARRAY_DATA = 'FADa',
SECTION_VARIABLE_SIZE_ARRAY_DATA = 'VADa',
SECTION_SORTED_INDEX_TABLE = 'DXIn',
SECTION_END_OF_DATA = 'DDEn'
};
struct r5_message_header {
uint32 magic;
uint32 checksum;
int32 flattened_size;
int32 what;
uint8 flags;
} _PACKED;
struct dano_section_header {
uint32 code;
int32 size;
uint8 data[0];
} _PACKED;
struct dano_message_header {
int32 what;
int32 padding;
} _PACKED;
typedef struct offset_table_s {
int32 indexTable;
int32 endOfData;
int64 padding;
} OffsetTable;
struct dano_single_item {
type_code type;
int32 item_size;
uint8 name_length;
char name[0];
} _PACKED;
struct dano_fixed_size_array {
type_code type;
int32 size_per_item;
uint8 name_length;
char name[0];
} _PACKED;
struct dano_variable_size_array {
type_code type;
int32 padding;
uint8 name_length;
char name[0];
} _PACKED;
inline int32
pad_to_8(int32 value)
{
return (value + 7) & ~7;
}
ssize_t
MessageAdapter::FlattenedSize(uint32 format, const BMessage *from)
{
switch (format) {
case MESSAGE_FORMAT_R5:
case MESSAGE_FORMAT_R5_SWAPPED:
return _R5FlattenedSize(from);
}
return -1;
}
status_t
MessageAdapter::Flatten(uint32 format, const BMessage *from, char *buffer,
ssize_t *size)
{
switch (format) {
case MESSAGE_FORMAT_R5:
case MESSAGE_FORMAT_R5_SWAPPED:
return _FlattenR5Message(format, from, buffer, size);
}
return B_ERROR;
}
status_t
MessageAdapter::Flatten(uint32 format, const BMessage *from, BDataIO *stream,
ssize_t *size)
{
switch (format) {
case MESSAGE_FORMAT_R5:
case MESSAGE_FORMAT_R5_SWAPPED:
{
ssize_t flattenedSize = _R5FlattenedSize(from);
char *buffer = (char *)malloc(flattenedSize);
if (!buffer)
return B_NO_MEMORY;
status_t result = _FlattenR5Message(format, from, buffer,
&flattenedSize);
if (result < B_OK) {
free(buffer);
return result;
}
ssize_t written = stream->Write(buffer, flattenedSize);
if (written != flattenedSize) {
free(buffer);
return (written >= 0 ? B_ERROR : written);
}
if (size)
*size = flattenedSize;
free(buffer);
return B_OK;
}
}
return B_ERROR;
}
status_t
MessageAdapter::Unflatten(uint32 format, BMessage *into, const char *buffer)
{
try {
switch (format) {
case MESSAGE_FORMAT_R5:
{
r5_message_header *header = (r5_message_header *)buffer;
BMemoryIO stream(buffer + sizeof(uint32),
header->flattened_size - sizeof(uint32));
return _UnflattenR5Message(format, into, &stream);
}
case MESSAGE_FORMAT_R5_SWAPPED:
{
r5_message_header *header = (r5_message_header *)buffer;
BMemoryIO stream(buffer + sizeof(uint32),
__swap_int32(header->flattened_size) - sizeof(uint32));
return _UnflattenR5Message(format, into, &stream);
}
case MESSAGE_FORMAT_DANO:
case MESSAGE_FORMAT_DANO_SWAPPED:
{
dano_section_header *header = (dano_section_header *)buffer;
ssize_t size = header->size;
if (header->code == MESSAGE_FORMAT_DANO_SWAPPED)
size = __swap_int32(size);
BMemoryIO stream(buffer + sizeof(uint32), size - sizeof(uint32));
return _UnflattenDanoMessage(format, into, &stream);
}
}
} catch (status_t error) {
into->MakeEmpty();
return error;
}
return B_NOT_A_MESSAGE;
}
status_t
MessageAdapter::Unflatten(uint32 format, BMessage *into, BDataIO *stream)
{
try {
switch (format) {
case MESSAGE_FORMAT_R5:
case MESSAGE_FORMAT_R5_SWAPPED:
return _UnflattenR5Message(format, into, stream);
case MESSAGE_FORMAT_DANO:
case MESSAGE_FORMAT_DANO_SWAPPED:
return _UnflattenDanoMessage(format, into, stream);
}
} catch (status_t error) {
into->MakeEmpty();
return error;
}
return B_NOT_A_MESSAGE;
}
ssize_t
MessageAdapter::_R5FlattenedSize(const BMessage *from)
{
BMessage::Private messagePrivate((BMessage *)from);
BMessage::message_header* header = messagePrivate.GetMessageHeader();
// header size (variable, depending on the flags)
ssize_t flattenedSize = sizeof(r5_message_header);
if (header->target != B_NULL_TOKEN)
flattenedSize += sizeof(int32);
if (header->reply_port >= 0 && header->reply_target != B_NULL_TOKEN
&& header->reply_team >= 0) {
// reply info + big flags
flattenedSize += sizeof(port_id) + sizeof(int32) + sizeof(team_id) + 4;
}
// field size
uint8 *data = messagePrivate.GetMessageData();
BMessage::field_header *field = messagePrivate.GetMessageFields();
for (uint32 i = 0; i < header->field_count; i++, field++) {
// flags and type
flattenedSize += 1 + sizeof(type_code);
#if 0
bool miniData = field->dataSize <= 255 && field->count <= 255;
#else
// ToDo: we don't know the R5 dataSize yet (padding)
bool miniData = false;
#endif
// item count
if (field->count > 1)
flattenedSize += (miniData ? sizeof(uint8) : sizeof(uint32));
// data size
flattenedSize += (miniData ? sizeof(uint8) : sizeof(size_t));
// name length and name
flattenedSize += 1 + min_c(field->name_length - 1, 255);
// data
if (field->flags & FIELD_FLAG_FIXED_SIZE)
flattenedSize += field->data_size;
else {
uint8 *source = data + field->offset + field->name_length;
for (uint32 i = 0; i < field->count; i++) {
ssize_t itemSize = *(ssize_t *)source + sizeof(ssize_t);
flattenedSize += pad_to_8(itemSize);
source += itemSize;
}
}
}
// pseudo field with flags 0
return flattenedSize + 1;
}
status_t
MessageAdapter::_FlattenR5Message(uint32 format, const BMessage *from,
char *buffer, ssize_t *size)
{
BMessage::Private messagePrivate((BMessage *)from);
BMessage::message_header *header = messagePrivate.GetMessageHeader();
uint8 *data = messagePrivate.GetMessageData();
r5_message_header *r5header = (r5_message_header *)buffer;
uint8 *pointer = (uint8 *)buffer + sizeof(r5_message_header);
r5header->magic = MESSAGE_FORMAT_R5;
r5header->what = from->what;
r5header->checksum = 0;
uint8 flags = R5_MESSAGE_FLAG_VALID;
if (header->target != B_NULL_TOKEN) {
*(int32 *)pointer = header->target;
pointer += sizeof(int32);
flags |= R5_MESSAGE_FLAG_INCLUDE_TARGET;
}
if (header->reply_port >= 0 && header->reply_target != B_NULL_TOKEN
&& header->reply_team >= 0) {
// reply info
*(port_id *)pointer = header->reply_port;
pointer += sizeof(port_id);
*(int32 *)pointer = header->reply_target;
pointer += sizeof(int32);
*(team_id *)pointer = header->reply_team;
pointer += sizeof(team_id);
// big flags
*pointer = (header->reply_target == B_PREFERRED_TOKEN ? 1 : 0);
pointer++;
*pointer = (header->flags & MESSAGE_FLAG_REPLY_REQUIRED ? 1 : 0);
pointer++;
*pointer = (header->flags & MESSAGE_FLAG_REPLY_DONE ? 1 : 0);
pointer++;
*pointer = (header->flags & MESSAGE_FLAG_IS_REPLY ? 1 : 0);
pointer++;
flags |= R5_MESSAGE_FLAG_INCLUDE_REPLY;
}
if (header->flags & MESSAGE_FLAG_HAS_SPECIFIERS)
flags |= R5_MESSAGE_FLAG_SCRIPT_MESSAGE;
r5header->flags = flags;
// store the header size - used for the checksum later
ssize_t headerSize = (addr_t)pointer - (addr_t)buffer;
// collect and add the data
BMessage::field_header *field = messagePrivate.GetMessageFields();
for (uint32 i = 0; i < header->field_count; i++, field++) {
flags = R5_FIELD_FLAG_VALID;
if (field->count == 1)
flags |= R5_FIELD_FLAG_SINGLE_ITEM;
// ToDo: we don't really know the data size now (padding missing)
if (field->data_size <= 255 && field->count <= 255)
;//flags |= R5_FIELD_FLAG_MINI_DATA;
if (field->flags & FIELD_FLAG_FIXED_SIZE)
flags |= R5_FIELD_FLAG_FIXED_SIZE;
*pointer = flags;
pointer++;
*(type_code *)pointer = field->type;
pointer += sizeof(type_code);
if (!(flags & R5_FIELD_FLAG_SINGLE_ITEM)) {
if (flags & R5_FIELD_FLAG_MINI_DATA) {
*pointer = (uint8)field->count;
pointer++;
} else {
*(int32 *)pointer = field->count;
pointer += sizeof(int32);
}
}
// we may have to adjust this to account for padding later
uint8 *fieldSize = pointer;
if (flags & R5_FIELD_FLAG_MINI_DATA) {
*pointer = (uint8)field->data_size;
pointer++;
} else {
*(ssize_t *)pointer = field->data_size;
pointer += sizeof(ssize_t);
}
// name
int32 nameLength = min_c(field->name_length - 1, 255);
*pointer = (uint8)nameLength;
pointer++;
strncpy((char *)pointer, (char *)data + field->offset, nameLength);
pointer += nameLength;
// data
uint8 *source = data + field->offset + field->name_length;
if (flags & R5_FIELD_FLAG_FIXED_SIZE) {
memcpy(pointer, source, field->data_size);
pointer += field->data_size;
} else {
uint8 *previous = pointer;
for (uint32 i = 0; i < field->count; i++) {
ssize_t itemSize = *(ssize_t *)source + sizeof(ssize_t);
memcpy(pointer, source, itemSize);
ssize_t paddedSize = pad_to_8(itemSize);
memset(pointer + itemSize, 0, paddedSize - itemSize);
pointer += paddedSize;
source += itemSize;
}
// adjust the field size to the padded value
if (flags & R5_FIELD_FLAG_MINI_DATA)
*fieldSize = (uint8)(pointer - previous);
else
*(ssize_t *)fieldSize = (pointer - previous);
}
}
// terminate the fields with a pseudo field with flags 0 (not valid)
*pointer = 0;
pointer++;
// calculate the flattened size from the pointers
r5header->flattened_size = (addr_t)pointer - (addr_t)buffer;
r5header->checksum = CalculateChecksum((uint8 *)(buffer + 8),
headerSize - 8);
if (size)
*size = r5header->flattened_size;
return B_OK;
}
status_t
MessageAdapter::_UnflattenR5Message(uint32 format, BMessage *into,
BDataIO *stream)
{
into->MakeEmpty();
BMessage::Private messagePrivate(into);
BMessage::message_header *header = messagePrivate.GetMessageHeader();
TReadHelper reader(stream);
if (format == MESSAGE_FORMAT_R5_SWAPPED)
reader.SetSwap(true);
// the stream is already advanced by the size of the "format"
r5_message_header r5header;
reader(((uint8 *)&r5header) + sizeof(uint32),
sizeof(r5header) - sizeof(uint32));
header->what = into->what = r5header.what;
if (r5header.flags & R5_MESSAGE_FLAG_INCLUDE_TARGET)
reader(&header->target, sizeof(header->target));
if (r5header.flags & R5_MESSAGE_FLAG_INCLUDE_REPLY) {
// reply info
reader(&header->reply_port, sizeof(header->reply_port));
reader(&header->reply_target, sizeof(header->reply_target));
reader(&header->reply_team, sizeof(header->reply_team));
// big flags
uint8 bigFlag;
reader(bigFlag);
if (bigFlag)
header->reply_target = B_PREFERRED_TOKEN;
reader(bigFlag);
if (bigFlag)
header->flags |= MESSAGE_FLAG_REPLY_REQUIRED;
reader(bigFlag);
if (bigFlag)
header->flags |= MESSAGE_FLAG_REPLY_DONE;
reader(bigFlag);
if (bigFlag)
header->flags |= MESSAGE_FLAG_IS_REPLY;
}
if (r5header.flags & R5_MESSAGE_FLAG_SCRIPT_MESSAGE)
header->flags |= MESSAGE_FLAG_HAS_SPECIFIERS;
uint8 flags;
reader(flags);
while (flags & R5_FIELD_FLAG_VALID) {
bool fixedSize = flags & R5_FIELD_FLAG_FIXED_SIZE;
bool miniData = flags & R5_FIELD_FLAG_MINI_DATA;
bool singleItem = flags & R5_FIELD_FLAG_SINGLE_ITEM;
type_code type;
reader(type);
int32 itemCount;
if (!singleItem) {
if (miniData) {
uint8 miniCount;
reader(miniCount);
itemCount = miniCount;
} else
reader(itemCount);
} else
itemCount = 1;
ssize_t dataSize;
if (miniData) {
uint8 miniSize;
reader(miniSize);
dataSize = miniSize;
} else
reader(dataSize);
if (dataSize <= 0)
return B_ERROR;
// name
uint8 nameLength;
reader(nameLength);
char nameBuffer[256];
reader(nameBuffer, nameLength);
nameBuffer[nameLength] = '\0';
uint8 *buffer = (uint8 *)malloc(dataSize);
uint8 *pointer = buffer;
reader(buffer, dataSize);
status_t result = B_OK;
ssize_t itemSize = 0;
if (fixedSize)
itemSize = dataSize / itemCount;
if (format == MESSAGE_FORMAT_R5) {
for (int32 i = 0; i < itemCount; i++) {
if (!fixedSize) {
itemSize = *(ssize_t *)pointer;
pointer += sizeof(ssize_t);
}
result = into->AddData(nameBuffer, type, pointer, itemSize,
fixedSize, itemCount);
if (result < B_OK) {
free(buffer);
return result;
}
if (fixedSize)
pointer += itemSize;
else
pointer += pad_to_8(itemSize + sizeof(ssize_t)) - sizeof(ssize_t);
}
} else {
for (int32 i = 0; i < itemCount; i++) {
if (!fixedSize) {
itemSize = __swap_int32(*(ssize_t *)pointer);
pointer += sizeof(ssize_t);
}
swap_data(type, pointer, itemSize, B_SWAP_ALWAYS);
result = into->AddData(nameBuffer, type, pointer, itemSize,
fixedSize, itemCount);
if (result < B_OK) {
free(buffer);
return result;
}
if (fixedSize)
pointer += itemSize;
else
pointer += pad_to_8(itemSize + sizeof(ssize_t)) - sizeof(ssize_t);
}
}
free(buffer);
// flags of next field or termination byte
reader(flags);
}
return B_OK;
}
status_t
MessageAdapter::_UnflattenDanoMessage(uint32 format, BMessage *into,
BDataIO *stream)
{
into->MakeEmpty();
TReadHelper reader(stream);
if (format == MESSAGE_FORMAT_DANO_SWAPPED)
reader.SetSwap(true);
ssize_t size;
reader(size);
dano_message_header header;
reader(header);
into->what = header.what;
size -= sizeof(dano_section_header) + sizeof(dano_message_header);
int32 offset = 0;
while (offset < size) {
dano_section_header sectionHeader;
reader(sectionHeader);
// be safe. this shouldn't be necessary but in some testcases it was.
sectionHeader.size = pad_to_8(sectionHeader.size);
if (offset + sectionHeader.size > size || sectionHeader.size < 0)
return B_BAD_DATA;
ssize_t fieldSize = sectionHeader.size - sizeof(dano_section_header);
uint8 *fieldBuffer = NULL;
if (fieldSize <= 0) {
// there may be no data. we shouldn't fail because of that
offset += sectionHeader.size;
continue;
}
fieldBuffer = (uint8 *)malloc(fieldSize);
if (fieldBuffer == NULL)
throw (status_t)B_NO_MEMORY;
reader(fieldBuffer, fieldSize);
switch (sectionHeader.code) {
case SECTION_OFFSET_TABLE:
case SECTION_TARGET_INFORMATION:
case SECTION_SORTED_INDEX_TABLE:
case SECTION_END_OF_DATA:
// discard
break;
case SECTION_SINGLE_ITEM_DATA: {
dano_single_item *field = (dano_single_item *)fieldBuffer;
int32 dataOffset = sizeof(dano_single_item)
+ field->name_length + 1;
dataOffset = pad_to_8(dataOffset);
if (offset + dataOffset + field->item_size > size)
return B_BAD_DATA;
// support for fixed size is not possible with a single item
bool fixedSize = false;
switch (field->type) {
case B_RECT_TYPE:
case B_POINT_TYPE:
case B_INT8_TYPE:
case B_INT16_TYPE:
case B_INT32_TYPE:
case B_INT64_TYPE:
case B_BOOL_TYPE:
case B_FLOAT_TYPE:
case B_DOUBLE_TYPE:
case B_POINTER_TYPE:
case B_MESSENGER_TYPE:
fixedSize = true;
break;
default:
break;
}
status_t result = into->AddData(field->name, field->type,
fieldBuffer + dataOffset, field->item_size, fixedSize);
if (result < B_OK) {
free(fieldBuffer);
throw result;
}
break;
}
case SECTION_FIXED_SIZE_ARRAY_DATA: {
dano_fixed_size_array *field
= (dano_fixed_size_array *)fieldBuffer;
int32 dataOffset = sizeof(dano_fixed_size_array)
+ field->name_length + 1;
dataOffset = pad_to_8(dataOffset);
int32 count = *(int32 *)(fieldBuffer + dataOffset);
dataOffset += 8; /* count and padding */
if (offset + dataOffset + count * field->size_per_item > size)
return B_BAD_DATA;
status_t result = B_OK;
for (int32 i = 0; i < count; i++) {
result = into->AddData(field->name, field->type,
fieldBuffer + dataOffset, field->size_per_item, true,
count);
if (result < B_OK) {
free(fieldBuffer);
throw result;
}
dataOffset += field->size_per_item;
}
break;
}
case SECTION_VARIABLE_SIZE_ARRAY_DATA: {
dano_variable_size_array *field
= (dano_variable_size_array *)fieldBuffer;
int32 dataOffset = sizeof(dano_variable_size_array)
+ field->name_length + 1;
dataOffset = pad_to_8(dataOffset);
int32 count = *(int32 *)(fieldBuffer + dataOffset);
dataOffset += sizeof(int32);
ssize_t totalSize = *(ssize_t *)(fieldBuffer + dataOffset);
dataOffset += sizeof(ssize_t);
int32 *endPoints = (int32 *)(fieldBuffer + dataOffset
+ totalSize);
status_t result = B_OK;
for (int32 i = 0; i < count; i++) {
int32 itemOffset = (i > 0 ? pad_to_8(endPoints[i - 1]) : 0);
result = into->AddData(field->name, field->type,
fieldBuffer + dataOffset + itemOffset,
endPoints[i] - itemOffset, false, count);
if (result < B_OK) {
free(fieldBuffer);
throw result;
}
}
break;
}
}
free(fieldBuffer);
offset += sectionHeader.size;
}
return B_OK;
}
} // namespace BPrivate

View File

@ -1,113 +0,0 @@
/*
* Copyright 2001-2005, Haiku.
* Distributed under the terms of the MIT License.
*
* Authors:
* Erik Jaesler (erik@cgsoftware.com)
*/
/** Extra messaging utility functions */
#include <string.h>
#include <ByteOrder.h>
#include <MessageUtils.h>
namespace BPrivate {
uint32
CalculateChecksum(const uint8 *buffer, int32 size)
{
uint32 sum = 0;
uint32 temp = 0;
while (size > 3) {
#if defined(__INTEL__)
sum += B_SWAP_INT32(*(int32 *)buffer);
#else
sum += *(int32 *)buffer;
#endif
buffer += 4;
size -= 4;
}
while (size > 0) {
temp = (temp << 8) + *buffer++;
size -= 1;
}
return sum + temp;
}
/* entry_ref support functions */
status_t
entry_ref_flatten(char *buffer, size_t *size, const entry_ref *ref)
{
if (*size < sizeof(ref->device) + sizeof(ref->directory))
return B_BUFFER_OVERFLOW;
memcpy((void *)buffer, (const void *)&ref->device, sizeof(ref->device));
buffer += sizeof(ref->device);
memcpy((void *)buffer, (const void *)&ref->directory, sizeof(ref->directory));
buffer += sizeof (ref->directory);
*size -= sizeof(ref->device) + sizeof(ref->directory);
size_t nameLength = 0;
if (ref->name) {
nameLength = strlen(ref->name) + 1;
if (*size < nameLength)
return B_BUFFER_OVERFLOW;
memcpy((void *)buffer, (const void *)ref->name, nameLength);
}
*size = sizeof(ref->device) + sizeof(ref->directory) + nameLength;
return B_OK;
}
status_t
entry_ref_unflatten(entry_ref *ref, const char *buffer, size_t size)
{
if (size < sizeof(ref->device) + sizeof(ref->directory)) {
*ref = entry_ref();
return B_BAD_VALUE;
}
memcpy((void *)&ref->device, (const void *)buffer, sizeof(ref->device));
buffer += sizeof (ref->device);
memcpy((void *)&ref->directory, (const void *)buffer, sizeof(ref->directory));
buffer += sizeof(ref->directory);
if (ref->device != ~(dev_t)0 && size > sizeof(ref->device)
+ sizeof(ref->directory)) {
ref->set_name(buffer);
if (ref->name == NULL) {
*ref = entry_ref();
return B_NO_MEMORY;
}
} else
ref->set_name(NULL);
return B_OK;
}
status_t
entry_ref_swap(char *buffer, size_t size)
{
if (size < sizeof(dev_t) + sizeof(ino_t))
return B_BAD_VALUE;
dev_t *dev = (dev_t *)buffer;
*dev = B_SWAP_INT32(*dev);
buffer += sizeof(dev_t);
ino_t *ino = (ino_t *)buffer;
*ino = B_SWAP_INT64(*ino);
return B_OK;
}
} // namespace BPrivate

View File

@ -1,39 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2005, Haiku
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: TypeConstants.cpp
// Description: These type constants are exported by libbe under R5.
// We need them for binary compatibility.
// See <TypeConstants.h>.
//------------------------------------------------------------------------------
const char *B_URL_HTTP = "application/x-vnd.Be.URL.http";
const char *B_URL_HTTPS = "application/x-vnd.Be.URL.https";
const char *B_URL_FTP = "application/x-vnd.Be.URL.ftp";
const char *B_URL_GOPHER = "application/x-vnd.Be.URL.gopher";
const char *B_URL_MAILTO = "application/x-vnd.Be.URL.mailto";
const char *B_URL_NEWS = "application/x-vnd.Be.URL.news";
const char *B_URL_NNTP = "application/x-vnd.Be.URL.nntp";
const char *B_URL_TELNET = "application/x-vnd.Be.URL.telnet";
const char *B_URL_RLOGIN = "application/x-vnd.Be.URL.rlogin";
const char *B_URL_TN3270 = "application/x-vnd.Be.URL.tn3270";
const char *B_URL_WAIS = "application/x-vnd.Be.URL.wais";
const char *B_URL_FILE = "application/x-vnd.Be.URL.file";

View File

@ -2,6 +2,8 @@ SubDir HAIKU_TOP src build libbe interface ;
UsePrivateBuildHeaders app interface shared ;
SEARCH_SOURCE += [ FDirName $(HAIKU_TOP) src kits interface ] ;
USES_BE_API on <libbe_build>interface_kit.o = true ;
BuildPlatformMergeObjectPIC <libbe_build>interface_kit.o :

View File

@ -1,101 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2004, Haiku
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Point.cpp
// Author: Frans van Nispen
// Description: BPoint represents a single x,y coordinate.
//------------------------------------------------------------------------------
// Standard Includes -----------------------------------------------------------
#include <math.h>
#include <stdio.h>
// System Includes -------------------------------------------------------------
#include <SupportDefs.h>
#include <Point.h>
#include <Rect.h>
const BPoint B_ORIGIN(0, 0);
void
BPoint::ConstrainTo(BRect r)
{
x = max_c(min_c(x, r.right), r.left);
y = max_c(min_c(y, r.bottom), r.top);
}
void
BPoint::PrintToStream() const
{
printf("BPoint(x:%.0f, y:%.0f)\n", x, y);
}
BPoint
BPoint::operator+(const BPoint& p) const
{
return BPoint(x + p.x, y + p.y);
}
BPoint
BPoint::operator-(const BPoint& p) const
{
return BPoint(x - p.x, y - p.y);
}
BPoint &
BPoint::operator+=(const BPoint& p)
{
x += p.x;
y += p.y;
return *this;
}
BPoint &
BPoint::operator-=(const BPoint& p)
{
x -= p.x;
y -= p.y;
return *this;
}
bool
BPoint::operator!=(const BPoint& p) const
{
return x != p.x || y != p.y;
}
bool
BPoint::operator==(const BPoint& p) const
{
return x == p.x && y == p.y;
}

View File

@ -1,279 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2004, Haiku, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Rect.cpp
// Author: Frans van Nispen (xlr8@tref.nl)
// Description: BRect represents a rectangular area.
//------------------------------------------------------------------------------
// Standard Includes -----------------------------------------------------------
#include <stdio.h>
// System Includes -------------------------------------------------------------
#include <Rect.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
void
BRect::SetLeftTop(const BPoint p)
{
left = p.x;
top = p.y;
}
//------------------------------------------------------------------------------
void
BRect::SetRightBottom(const BPoint p)
{
right = p.x;
bottom = p.y;
}
//------------------------------------------------------------------------------
void
BRect::SetLeftBottom(const BPoint p)
{
left = p.x;
bottom = p.y;
}
//------------------------------------------------------------------------------
void
BRect::SetRightTop(const BPoint p)
{
right = p.x;
top = p.y;
}
//------------------------------------------------------------------------------
void
BRect::InsetBy(BPoint point)
{
left += point.x;
right -= point.x;
top += point.y;
bottom -= point.y;
}
//------------------------------------------------------------------------------
void
BRect::InsetBy(float dx, float dy)
{
left += dx;
right -= dx;
top += dy;
bottom -= dy;
}
//------------------------------------------------------------------------------
BRect&
BRect::InsetBySelf(BPoint point)
{
InsetBy(point);
return *this;
}
//------------------------------------------------------------------------------
BRect&
BRect::InsetBySelf(float dx, float dy)
{
InsetBy(dx, dy);
return *this;
}
//------------------------------------------------------------------------------
BRect
BRect::InsetByCopy(BPoint point)
{
BRect copy(*this);
copy.InsetBy(point);
return copy;
}
//------------------------------------------------------------------------------
BRect
BRect::InsetByCopy(float dx, float dy)
{
BRect copy(*this);
copy.InsetBy(dx, dy);
return copy;
}
//------------------------------------------------------------------------------
void
BRect::OffsetBy(BPoint point)
{
left += point.x;
right += point.x;
top += point.y;
bottom += point.y;
}
//------------------------------------------------------------------------------
void
BRect::OffsetBy(float dx, float dy)
{
left += dx;
right += dx;
top += dy;
bottom += dy;
}
//------------------------------------------------------------------------------
BRect&
BRect::OffsetBySelf(BPoint point)
{
OffsetBy(point);
return *this;
}
//------------------------------------------------------------------------------
BRect&
BRect::OffsetBySelf(float dx, float dy)
{
OffsetBy(dx, dy);
return *this;
}
//------------------------------------------------------------------------------
BRect
BRect::OffsetByCopy(BPoint point)
{
BRect copy(*this);
copy.OffsetBy(point);
return copy;
}
//------------------------------------------------------------------------------
BRect
BRect::OffsetByCopy(float dx, float dy)
{
BRect copy(*this);
copy.OffsetBy(dx, dy);
return copy;
}
//------------------------------------------------------------------------------
void
BRect::OffsetTo(BPoint point)
{
right = (right - left) + point.x;
left = point.x;
bottom = (bottom - top) + point.y;
top = point.y;
}
//------------------------------------------------------------------------------
void
BRect::OffsetTo(float x, float y)
{
right = (right - left) + x;
left = x;
bottom = (bottom - top) + y;
top=y;
}
//------------------------------------------------------------------------------
BRect&
BRect::OffsetToSelf(BPoint point)
{
OffsetTo(point);
return *this;
}
//------------------------------------------------------------------------------
BRect&
BRect::OffsetToSelf(float dx, float dy)
{
OffsetTo(dx, dy);
return *this;
}
//------------------------------------------------------------------------------
BRect
BRect::OffsetToCopy(BPoint point)
{
BRect copy(*this);
copy.OffsetTo(point);
return copy;
}
//------------------------------------------------------------------------------
BRect
BRect::OffsetToCopy(float dx, float dy)
{
BRect copy(*this);
copy.OffsetTo(dx, dy);
return copy;
}
//------------------------------------------------------------------------------
void
BRect::PrintToStream() const
{
printf("BRect(l:%.1f, t:%.1f, r:%.1f, b:%.1f)\n", left, top, right, bottom);
}
//------------------------------------------------------------------------------
bool
BRect::operator==(BRect rect) const
{
return left == rect.left && right == rect.right &&
top == rect.top && bottom == rect.bottom;
}
//------------------------------------------------------------------------------
bool
BRect::operator!=(BRect rect) const
{
return !(*this == rect);
}
//------------------------------------------------------------------------------
BRect
BRect::operator&(BRect rect) const
{
return BRect(max_c(left, rect.left), max_c(top, rect.top),
min_c(right, rect.right), min_c(bottom, rect.bottom));
}
//------------------------------------------------------------------------------
BRect
BRect::operator|(BRect rect) const
{
return BRect(min_c(left, rect.left), min_c(top, rect.top),
max_c(right, rect.right), max_c(bottom, rect.bottom));
}
//------------------------------------------------------------------------------
bool
BRect::Intersects(BRect rect) const
{
if (!IsValid() || !rect.IsValid())
return false;
return !(rect.left > right || rect.right < left
|| rect.top > bottom || rect.bottom < top);
}
//------------------------------------------------------------------------------
bool
BRect::Contains(BPoint point) const
{
return point.x >= left && point.x <= right
&& point.y >= top && point.y <= bottom;
}
//------------------------------------------------------------------------------
bool
BRect::Contains(BRect rect) const
{
return rect.left >= left && rect.right <= right
&& rect.top >= top && rect.bottom <= bottom;
}
//------------------------------------------------------------------------------
/*
* $Log $
*
* $Id $
*
*/

View File

@ -1,527 +0,0 @@
/*
* Copyright 2003-2007, Haiku. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Stefano Ceccherini (burton666@libero.it)
* Stephan Aßmus <superstippi@gmx.de>
*/
#include <Region.h>
#include <stdlib.h>
#include <string.h>
#include <Debug.h>
#include "clipping.h"
#include "RegionSupport.h"
const static int32 kDataBlockSize = 8;
/*! \brief Initializes a region. The region will have no rects,
and its fBounds will be invalid.
*/
BRegion::BRegion()
: fCount(0)
, fDataSize(0)
, fBounds((clipping_rect){ 0, 0, 0, 0 })
, fData(NULL)
{
_SetSize(kDataBlockSize);
}
/*! \brief Initializes a region to be a copy of another.
\param region The region to copy.
*/
BRegion::BRegion(const BRegion& region)
: fCount(0)
, fDataSize(0)
, fBounds((clipping_rect){ 0, 0, 0, 0 })
, fData(NULL)
{
*this = region;
}
/*! \brief Initializes a region to contain a BRect.
\param rect The BRect to set the region to.
*/
BRegion::BRegion(const BRect rect)
: fCount(0)
, fDataSize(1)
, fBounds((clipping_rect){ 0, 0, 0, 0 })
, fData(&fBounds)
{
if (!rect.IsValid())
return;
fBounds = _ConvertToInternal(rect);
fCount = 1;
}
// NOTE: private constructor
/*! \brief Initializes a region to contain a clipping_rect.
\param rect The clipping_rect to set the region to, already in
internal rect format.
*/
BRegion::BRegion(const clipping_rect& rect)
: fCount(1)
, fDataSize(1)
, fBounds(rect)
, fData(&fBounds)
{
}
/*! \brief Frees the allocated memory.
*/
BRegion::~BRegion()
{
if (fData != &fBounds)
free(fData);
}
// #pragma mark -
/*! \brief Modifies the region to be a copy of the given BRegion.
\param region the BRegion to copy.
\return This function always returns \c *this.
*/
BRegion &
BRegion::operator=(const BRegion &region)
{
if (&region == this)
return *this;
// handle reallocation if we're too small to contain
// the other region
if (_SetSize(region.fDataSize)) {
memcpy(fData, region.fData, region.fCount * sizeof(clipping_rect));
fBounds = region.fBounds;
fCount = region.fCount;
}
return *this;
}
/*! \brief Set the region to contain just the given BRect.
\param newBounds A BRect.
*/
void
BRegion::Set(BRect newBounds)
{
Set(_Convert(newBounds));
}
/*! \brief Set the region to contain just the given clipping_rect.
\param newBounds A clipping_rect.
*/
void
BRegion::Set(clipping_rect newBounds)
{
_SetSize(1);
if (valid_rect(newBounds) && fData) {
fCount = 1;
// cheap convert to internal rect format
newBounds.right++;
newBounds.bottom++;
fData[0] = fBounds = newBounds;
} else
MakeEmpty();
}
// #pragma mark -
/*! \brief Returns the bounds of the region.
\return A BRect which represents the bounds of the region.
*/
BRect
BRegion::Frame() const
{
return BRect(fBounds.left, fBounds.top,
fBounds.right - 1, fBounds.bottom - 1);
}
/*! \brief Returns the bounds of the region as a clipping_rect (which has integer coordinates).
\return A clipping_rect which represents the bounds of the region.
*/
clipping_rect
BRegion::FrameInt() const
{
return (clipping_rect){ fBounds.left, fBounds.top,
fBounds.right - 1, fBounds.bottom - 1 };
}
/*! \brief Returns the regions's BRect at the given index.
\param index The index (zero based) of the wanted rectangle.
\return If the given index is valid, it returns the BRect at that index,
otherwise, it returns an invalid BRect.
*/
BRect
BRegion::RectAt(int32 index) /*const*/
{
if (index >= 0 && index < fCount) {
const clipping_rect& r = fData[index];
return BRect(r.left, r.top, r.right - 1, r.bottom - 1);
}
return BRect();
// an invalid BRect
}
/*! \brief Returns the regions's clipping_rect at the given index.
\param index The index (zero based) of the wanted rectangle.
\return If the given index is valid, it returns the clipping_rect at that index,
otherwise, it returns an invalid clipping_rect.
*/
clipping_rect
BRegion::RectAtInt(int32 index) /*const*/
{
if (index >= 0 && index < fCount) {
const clipping_rect& r = fData[index];
return (clipping_rect){ r.left, r.top, r.right - 1, r.bottom - 1 };
}
return (clipping_rect){ 1, 1, 0, 0 };
// an invalid clipping_rect
}
/*! \brief Counts the region rects.
\return An int32 which is the total number of rects in the region.
*/
int32
BRegion::CountRects() /*const*/
{
return fCount;
}
// #pragma mark -
/*! \brief Check if the region has any area in common with the given BRect.
\param rect The BRect to check the region against to.
\return \ctrue if the region has any area in common with the BRect, \cfalse if not.
*/
bool
BRegion::Intersects(BRect rect) const
{
return Intersects(_Convert(rect));
}
/*! \brief Check if the region has any area in common with the given clipping_rect.
\param rect The clipping_rect to check the region against to.
\return \ctrue if the region has any area in common with the clipping_rect, \cfalse if not.
*/
bool
BRegion::Intersects(clipping_rect rect) const
{
// cheap convert to internal rect format
rect.right ++;
rect.bottom ++;
int result = Support::XRectInRegion(this, rect);
return result > Support::RectangleOut;
}
/*! \brief Check if the region contains the given BPoint.
\param pt The BPoint to be checked.
\return \ctrue if the region contains the BPoint, \cfalse if not.
*/
bool
BRegion::Contains(BPoint point) const
{
return Support::XPointInRegion(this, (int)point.x, (int)point.y);
}
/*! \brief Check if the region contains the given coordinates.
\param x The \cx coordinate of the point to be checked.
\param y The \cy coordinate of the point to be checked.
\return \ctrue if the region contains the point, \cfalse if not.
*/
bool
BRegion::Contains(int32 x, int32 y) /*const*/
{
return Support::XPointInRegion(this, x, y);
}
/*! \brief Prints the BRegion to stdout.
*/
void
BRegion::PrintToStream() const
{
Frame().PrintToStream();
for (long i = 0; i < fCount; i++) {
clipping_rect *rect = &fData[i];
printf("data[%ld] = BRect(l:%" B_PRId32 ".0, t:%" B_PRId32 ".0, r:%"
B_PRId32 ".0, b:%" B_PRId32 ".0)\n",
i, rect->left, rect->top, rect->right - 1, rect->bottom - 1);
}
}
// #pragma mark -
/*! \brief Offsets all region's rects, and bounds by the given values.
\param dh The horizontal offset.
\param dv The vertical offset.
*/
void
BRegion::OffsetBy(int32 x, int32 y)
{
if (x == 0 && y == 0)
return;
if (fCount > 0) {
if (fData != &fBounds) {
for (long i = 0; i < fCount; i++)
offset_rect(fData[i], x, y);
}
offset_rect(fBounds, x, y);
}
}
/*! \brief Empties the region, so that it doesn't include any rect, and invalidates its bounds.
*/
void
BRegion::MakeEmpty()
{
fBounds = (clipping_rect){ 0, 0, 0, 0 };
fCount = 0;
}
// #pragma mark -
/*! \brief Modifies the region, so that it includes the given BRect.
\param rect The BRect to be included by the region.
*/
void
BRegion::Include(BRect rect)
{
Include(_Convert(rect));
}
/*! \brief Modifies the region, so that it includes the given clipping_rect.
\param rect The clipping_rect to be included by the region.
*/
void
BRegion::Include(clipping_rect rect)
{
// convert to internal rect format
rect.right ++;
rect.bottom ++;
// use private clipping_rect constructor which avoids malloc()
BRegion t(rect);
BRegion result;
Support::XUnionRegion(this, &t, &result);
_AdoptRegionData(result);
}
/*! \brief Modifies the region, so that it includes the area of the given region.
\param region The region to be included.
*/
void
BRegion::Include(const BRegion* region)
{
BRegion result;
Support::XUnionRegion(this, region, &result);
_AdoptRegionData(result);
}
// #pragma mark -
/*! \brief Modifies the region, excluding the area represented by the given BRect.
\param rect The BRect to be excluded.
*/
void
BRegion::Exclude(BRect rect)
{
Exclude(_Convert(rect));
}
/*! \brief Modifies the region, excluding the area represented by the given clipping_rect.
\param rect The clipping_rect to be excluded.
*/
void
BRegion::Exclude(clipping_rect rect)
{
// convert to internal rect format
rect.right ++;
rect.bottom ++;
// use private clipping_rect constructor which avoids malloc()
BRegion t(rect);
BRegion result;
Support::XSubtractRegion(this, &t, &result);
_AdoptRegionData(result);
}
/*! \brief Modifies the region, excluding the area contained in the given
BRegion.
\param region The BRegion to be excluded.
*/
void
BRegion::Exclude(const BRegion* region)
{
BRegion result;
Support::XSubtractRegion(this, region, &result);
_AdoptRegionData(result);
}
// #pragma mark -
/*! \brief Modifies the region, so that it will contain just the area
in common with the given BRegion.
\param region the BRegion to intersect to.
*/
void
BRegion::IntersectWith(const BRegion* region)
{
BRegion result;
Support::XIntersectRegion(this, region, &result);
_AdoptRegionData(result);
}
// #pragma mark -
/*! \brief Takes over the data of a region and marks that region empty.
\param region The region to adopt the data from.
*/
void
BRegion::_AdoptRegionData(BRegion& region)
{
fCount = region.fCount;
fDataSize = region.fDataSize;
fBounds = region.fBounds;
if (fData != &fBounds)
free(fData);
if (region.fData != &region.fBounds)
fData = region.fData;
else
fData = &fBounds;
// NOTE: MakeEmpty() is not called since _AdoptRegionData is only
// called with internally allocated regions, so they don't need to
// be left in a valid state.
region.fData = NULL;
// region.MakeEmpty();
}
/*! \brief Reallocate the memory in the region.
\param newSize The amount of rectangles that the region should be
able to hold.
*/
bool
BRegion::_SetSize(long newSize)
{
// we never shrink the size
newSize = max_c(fDataSize, newSize);
if (newSize == fDataSize)
return true;
// align newSize to multiple of kDataBlockSize
newSize = ((newSize + kDataBlockSize - 1) / kDataBlockSize) * kDataBlockSize;
if (newSize > 0) {
if (fData == &fBounds) {
fData = (clipping_rect*)malloc(newSize * sizeof(clipping_rect));
fData[0] = fBounds;
} else if (fData) {
clipping_rect* resizedData = (clipping_rect*)realloc(fData,
newSize * sizeof(clipping_rect));
if (!resizedData) {
// failed to resize, but we cannot keep the
// previous state of the object
free(fData);
fData = NULL;
} else
fData = resizedData;
} else
fData = (clipping_rect*)malloc(newSize * sizeof(clipping_rect));
} else {
// just an empty region, but no error
MakeEmpty();
return true;
}
if (!fData) {
// allocation actually failed
fDataSize = 0;
MakeEmpty();
return false;
}
fDataSize = newSize;
return true;
}
clipping_rect
BRegion::_Convert(const BRect& rect) const
{
return (clipping_rect){ (int)floorf(rect.left), (int)floorf(rect.top),
(int)ceilf(rect.right), (int)ceilf(rect.bottom) };
}
clipping_rect
BRegion::_ConvertToInternal(const BRect& rect) const
{
return (clipping_rect){ (int)floorf(rect.left), (int)floorf(rect.top),
(int)ceilf(rect.right) + 1, (int)ceilf(rect.bottom) + 1 };
}
clipping_rect
BRegion::_ConvertToInternal(const clipping_rect& rect) const
{
return (clipping_rect){ rect.left, rect.top,
rect.right + 1, rect.bottom + 1 };
}

File diff suppressed because it is too large Load Diff

View File

@ -1078,7 +1078,7 @@ BEntry::Dump(const char *name)
&& _kern_read_stat(fDirFd, NULL, false, &st,
sizeof(struct stat)) == B_OK) {
printf("dir.device == %d\n", (int)st.st_dev);
printf("dir.inode == %" B_PRIdINO "\n", st.st_ino);
printf("dir.inode == %lld\n", (long long)st.st_ino);
} else {
printf("dir == NullFd\n");
}

View File

@ -1,110 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file EntryList.cpp
BEntryList implementation.
*/
#include <EntryList.h>
// constructor
//! Creates a BEntryList.
/*! Does nothing at this time.
*/
BEntryList::BEntryList()
{
}
// destructor
//! Frees all resources associated with this BEntryList.
/*! Does nothing at this time.
*/
BEntryList::~BEntryList()
{
}
// GetNextEntry
/*! \fn status_t BEntryList::GetNextEntry(BEntry *entry, bool traverse)
\brief Returns the BEntryList's next entry as a BEntry.
Places the next entry in the list in \a entry, traversing symlinks if
\a traverse is \c true.
\param entry a pointer to a BEntry to be initialized with the found entry
\param traverse specifies whether to follow it, if the found entry
is a symbolic link.
\note The iterator used by this method is the same one used by
GetNextRef(), GetNextDirents(), Rewind() and CountEntries().
\return
- \c B_OK if successful,
- \c B_ENTRY_NOT_FOUND when at the end of the list,
- another error code (depending on the implementation of the derived class)
if an error occured.
*/
// GetNextRef
/*! \fn status_t BEntryList::GetNextRef(entry_ref *ref)
\brief Returns the BEntryList's next entry as an entry_ref.
Places an entry_ref to the next entry in the list into \a ref.
\param ref a pointer to an entry_ref to be filled in with the data of the
found entry
\note The iterator used by this method is the same one used by
GetNextEntry(), GetNextDirents(), Rewind() and CountEntries().
\return
- \c B_OK if successful,
- \c B_ENTRY_NOT_FOUND when at the end of the list,
- another error code (depending on the implementation of the derived class)
if an error occured.
*/
// GetNextDirents
/*! \fn int32 BEntryList::GetNextDirents(struct dirent *buf, size_t length, int32 count)
\brief Returns the BEntryList's next entries as dirent structures.
Reads a number of entries into the array of dirent structures pointed to by
\a buf. Reads as many but no more than \a count entries, as many entries as
remain, or as many entries as will fit into the array at \a buf with given
length \a length (in bytes), whichever is smallest.
\param buf a pointer to a buffer to be filled with dirent structures of
the found entries
\param length the maximal number of entries to be read.
\note The iterator used by this method is the same one used by
GetNextEntry(), GetNextRef(), Rewind() and CountEntries().
\return
- The number of dirent structures stored in the buffer, 0 when there are
no more entries to be read.
- an error code (depending on the implementation of the derived class)
if an error occured.
*/
// Rewind
/*! \fn status_t BEntryList::Rewind()
\brief Rewinds the list pointer to the beginning of the list.
\return
- \c B_OK if successful,
- an error code (depending on the implementation of the derived class)
if an error occured.
*/
// CountEntries
/*! \fn int32 BEntryList::CountEntries()
\brief Returns the number of entries in the list
\return
- the number of entries in the list,
- an error code (depending on the implementation of the derived class)
if an error occured.
*/
/*! Currently unused */
void BEntryList::_ReservedEntryList1() {}
void BEntryList::_ReservedEntryList2() {}
void BEntryList::_ReservedEntryList3() {}
void BEntryList::_ReservedEntryList4() {}
void BEntryList::_ReservedEntryList5() {}
void BEntryList::_ReservedEntryList6() {}
void BEntryList::_ReservedEntryList7() {}
void BEntryList::_ReservedEntryList8() {}

View File

@ -1,5 +1,5 @@
//----------------------------------------------------------------------
// This software is part of the Haiku distribution and is covered
// This software is part of the Haiku distribution and is covered
// by the MIT license.
//---------------------------------------------------------------------
/*!
@ -81,7 +81,7 @@ BFile::BFile(const BEntry *entry, uint32 openMode)
// constructor
/*! \brief Creates a BFile and initializes it to the file referred to by
the supplied path name and according to the specified open mode.
\param path the file's path name
\param path the file's path name
\param openMode the mode in which the file should be opened
\see SetTo() for values for \a openMode
*/
@ -167,9 +167,9 @@ BFile::SetTo(const entry_ref *ref, uint32 openMode)
set_fd(fd);
fMode = openMode;
fCStatus = B_OK;
fcntl(fd, F_SETFD, FD_CLOEXEC);
} else
fCStatus = fd;
@ -211,7 +211,7 @@ BFile::SetTo(const BEntry *entry, uint32 openMode)
set_fd(fd);
fMode = openMode;
fCStatus = B_OK;
fcntl(fd, F_SETFD, FD_CLOEXEC);
} else
fCStatus = fd;
@ -222,7 +222,7 @@ BFile::SetTo(const BEntry *entry, uint32 openMode)
// SetTo
/*! \brief Re-initializes the BFile to the file referred to by the
supplied path name and according to the specified open mode.
\param path the file's path name
\param path the file's path name
\param openMode the mode in which the file should be opened
\return
- \c B_OK: Everything went fine.
@ -249,7 +249,7 @@ BFile::SetTo(const char *path, uint32 openMode)
set_fd(fd);
fMode = openMode;
fCStatus = B_OK;
fcntl(fd, F_SETFD, FD_CLOEXEC);
} else
fCStatus = fd;
@ -291,7 +291,7 @@ BFile::SetTo(const BDirectory *dir, const char *path, uint32 openMode)
set_fd(fd);
fMode = openMode;
fCStatus = B_OK;
fcntl(fd, F_SETFD, FD_CLOEXEC);
} else
fCStatus = fd;
@ -461,6 +461,14 @@ BFile::SetSize(off_t size)
return set_stat(statData, B_STAT_SIZE);
}
status_t
BFile::GetSize(off_t* size) const
{
return BStatable::GetSize(size);
}
// =
//! Assigns another BFile to this BFile.
/*! If the other BFile is uninitialized, this one will be too. Otherwise it

View File

@ -1,138 +0,0 @@
/*
* Copyright 2009-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#include <FileIO.h>
#include <errno.h>
#include <stdio.h>
BFileIO::BFileIO(FILE* file, bool takeOverOwnership)
:
fFile(file),
fOwnsFile(takeOverOwnership)
{
}
BFileIO::~BFileIO()
{
if (fOwnsFile && fFile != NULL)
fclose(fFile);
}
ssize_t
BFileIO::Read(void *buffer, size_t size)
{
errno = B_OK;
ssize_t bytesRead = fread(buffer, 1, size, fFile);
return bytesRead >= 0 ? bytesRead : errno;
}
ssize_t
BFileIO::Write(const void *buffer, size_t size)
{
errno = B_OK;
ssize_t bytesRead = fwrite(buffer, 1, size, fFile);
return bytesRead >= 0 ? bytesRead : errno;
}
ssize_t
BFileIO::ReadAt(off_t position, void *buffer, size_t size)
{
// save the old position and seek to the requested one
off_t oldPosition = _Seek(position, SEEK_SET);
if (oldPosition < 0)
return oldPosition;
// read
ssize_t result = BFileIO::Read(buffer, size);
// seek back
fseeko(fFile, oldPosition, SEEK_SET);
return result;
}
ssize_t
BFileIO::WriteAt(off_t position, const void *buffer, size_t size)
{
// save the old position and seek to the requested one
off_t oldPosition = _Seek(position, SEEK_SET);
if (oldPosition < 0)
return oldPosition;
// write
ssize_t result = BFileIO::Write(buffer, size);
// seek back
fseeko(fFile, oldPosition, SEEK_SET);
return result;
}
off_t
BFileIO::Seek(off_t position, uint32 seekMode)
{
if (fseeko(fFile, position, seekMode) < 0)
return errno;
return BFileIO::Position();
}
off_t
BFileIO::Position() const
{
off_t result = ftello(fFile);
return result >= 0 ? result : errno;
}
status_t
BFileIO::SetSize(off_t size)
{
return B_UNSUPPORTED;
}
status_t
BFileIO::GetSize(off_t* _size) const
{
// save the current position and seek to the end
off_t position = _Seek(0, SEEK_END);
if (position < 0)
return position;
// get the size (position at end) and seek back
off_t size = _Seek(position, SEEK_SET);
if (size < 0)
return size;
*_size = size;
return B_OK;
}
off_t
BFileIO::_Seek(off_t position, uint32 seekMode) const
{
// save the current position
off_t oldPosition = ftello(fFile);
if (oldPosition < 0)
return errno;
// seek to the requested position
if (fseeko(fFile, position, seekMode) < 0)
return errno;
return oldPosition;
}

View File

@ -1,45 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the Haiku distribution and is covered
// by the MIT license.
//---------------------------------------------------------------------
/*!
\file FindDirectory.cpp
find_directory() implementations.
*/
#include <FindDirectory.h>
#include <Path.h>
#include <Volume.h>
// find_directory
//! Returns a path of a directory specified by a directory_which constant.
/*! \param which the directory_which constant specifying the directory
\param path a BPath object to be initialized to the directory's path
\param createIt \c true, if the directory shall be created, if it doesn't
already exist, \c false otherwise.
\param volume the volume on which the directory is located
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL \a path.
- another error code
*/
status_t
find_directory(directory_which which, BPath *path, bool createIt,
BVolume *volume)
{
if (path == NULL)
return B_BAD_VALUE;
dev_t device = (dev_t)-1;
if (volume && volume->InitCheck() == B_OK)
device = volume->Device();
char buffer[B_PATH_NAME_LENGTH];
status_t error = find_directory(which, device, createIt, buffer, B_PATH_NAME_LENGTH);
if (error == B_OK)
error = path->SetTo(buffer);
return error;
}

View File

@ -4,6 +4,9 @@ UsePrivateBuildHeaders app kernel shared storage ;
SEARCH_SOURCE += [ FDirName $(SUBDIR) mime ] ;
SEARCH_SOURCE += [ FDirName $(HAIKU_TOP) src kits storage ] ;
SEARCH_SOURCE += [ FDirName $(HAIKU_TOP) src kits storage mime ] ;
USES_BE_API on <libbe_build>storage_kit.o = true ;
BuildPlatformMergeObjectPIC <libbe_build>storage_kit.o :

View File

@ -1,175 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file OffsetFile.cpp
OffsetFile implementation.
*/
#include <stdio.h>
#include "OffsetFile.h"
namespace BPrivate {
namespace Storage {
// constructor
OffsetFile::OffsetFile()
: fFile(NULL),
fOffset(0),
fCurrentPosition(0)
{
}
// constructor
OffsetFile::OffsetFile(BFile *file, off_t offset)
: fFile(NULL),
fOffset(0),
fCurrentPosition(0)
{
SetTo(file, offset);
}
// destructor
OffsetFile::~OffsetFile()
{
}
// SetTo
status_t
OffsetFile::SetTo(BFile *file, off_t offset)
{
Unset();
fFile = file;
fOffset = offset;
return fFile->InitCheck();
}
// Unset
void
OffsetFile::Unset()
{
fFile = NULL;
fOffset = 0;
fCurrentPosition = 0;
}
// InitCheck
status_t
OffsetFile::InitCheck() const
{
return (fFile ? fFile->InitCheck() : B_NO_INIT);
}
// File
BFile *
OffsetFile::File() const
{
return fFile;
}
// ReadAt
ssize_t
OffsetFile::ReadAt(off_t pos, void *buffer, size_t size)
{
status_t error = InitCheck();
ssize_t result = 0;
if (error == B_OK)
result = fFile->ReadAt(pos + fOffset, buffer, size);
return (error == B_OK ? result : error);
}
// WriteAt
ssize_t
OffsetFile::WriteAt(off_t pos, const void *buffer, size_t size)
{
status_t error = InitCheck();
ssize_t result = 0;
if (error == B_OK)
result = fFile->WriteAt(pos + fOffset, buffer, size);
return (error == B_OK ? result : error);
}
// Seek
off_t
OffsetFile::Seek(off_t position, uint32 seekMode)
{
off_t result = B_BAD_VALUE;
status_t error = InitCheck();
if (error == B_OK) {
switch (seekMode) {
case SEEK_SET:
if (position >= 0)
result = fCurrentPosition = position;
break;
case SEEK_END:
{
off_t size;
error = GetSize(&size);
if (error == B_OK) {
if (size + position >= 0)
result = fCurrentPosition = size + position;
}
break;
}
case SEEK_CUR:
if (fCurrentPosition + position >= 0)
result = fCurrentPosition += position;
break;
default:
break;
}
}
return (error == B_OK ? result : error);
}
// Position
off_t
OffsetFile::Position() const
{
return fCurrentPosition;
}
// SetSize
status_t
OffsetFile::SetSize(off_t size)
{
status_t error = (size >= 0 ? B_OK : B_BAD_VALUE );
if (error == B_OK)
error = InitCheck();
if (error == B_OK)
error = fFile->SetSize(size + fOffset);
return error;
}
// GetSize
status_t
OffsetFile::GetSize(off_t *size) const
{
status_t error = (size ? B_OK : B_BAD_VALUE );
if (error == B_OK)
error = InitCheck();
if (error == B_OK)
error = fFile->GetSize(size);
if (error == B_OK) {
*size -= fOffset;
if (*size < 0)
*size = 0;
}
return error;
}
// Offset
off_t
OffsetFile::Offset() const
{
return fOffset;
}
}; // namespace Storage
}; // namespace BPrivate

View File

@ -1,761 +0,0 @@
/*
* Copyright 2002-2008, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Tyler Dauwalder, tyler@dauwalder.net
* Bill Hayden, haydentech@users.sourceforge.net
* Erik Jakowatz
* Ingo Weinhold, ingo_weinhold@gmx.de
*/
/*!
\file Path.cpp
BPath implementation.
*/
#include <Path.h>
#include <new>
#include <Directory.h>
#include <Entry.h>
#include <StorageDefs.h>
#include <String.h>
#include <syscalls.h>
#include "storage_support.h"
using namespace std;
//! Creates an uninitialized BPath object.
BPath::BPath()
:
fName(NULL),
fCStatus(B_NO_INIT)
{
}
/*! Creates a copy of the given BPath object.
\param path the object to be copied
*/
BPath::BPath(const BPath &path)
:
fName(NULL),
fCStatus(B_NO_INIT)
{
*this = path;
}
/*! \brief Creates a BPath object and initializes it to the filesystem entry
specified by the given entry_ref struct.
\param ref the entry_ref
*/
BPath::BPath(const entry_ref *ref)
:
fName(NULL),
fCStatus(B_NO_INIT)
{
SetTo(ref);
}
/*! Creates a BPath object and initializes it to the filesystem entry
specified by the given BEntry object.
\param entry the BEntry object
*/
BPath::BPath(const BEntry *entry)
:
fName(NULL),
fCStatus(B_NO_INIT)
{
SetTo(entry);
}
/*! \brief Creates a BPath object and initializes it to the specified path or
path and filename combination.
\param dir The base component of the pathname. May be absolute or relative.
If relative, it is reckoned off the current working directory.
\param leaf The (optional) leaf component of the pathname. Must be
relative. The value of leaf is concatenated to the end of \a dir
(a "/" will be added as a separator, if necessary).
\param normalize boolean flag used to force normalization; normalization
may occur even if false (see \ref MustNormalize).
*/
BPath::BPath(const char *dir, const char *leaf, bool normalize)
:
fName(NULL),
fCStatus(B_NO_INIT)
{
SetTo(dir, leaf, normalize);
}
/*! \brief Creates a BPath object and initializes it to the specified directory
and filename combination.
\param dir Refers to the directory that provides the base component of the
pathname.
\param leaf The (optional) leaf component of the pathname. Must be
relative. The value of leaf is concatenated to the end of \a dir
(a "/" will be added as a separator, if necessary).
\param normalize boolean flag used to force normalization; normalization
may occur even if false (see \ref MustNormalize).
*/
BPath::BPath(const BDirectory *dir, const char *leaf, bool normalize)
:
fName(NULL),
fCStatus(B_NO_INIT)
{
SetTo(dir, leaf, normalize);
}
//! Destroys the BPath object and frees any of its associated resources.
BPath::~BPath()
{
Unset();
}
/*! Returns the status of the most recent construction or SetTo() call.
\return \c B_OK, if the BPath object is properly initialized, an error
code otherwise.
*/
status_t
BPath::InitCheck() const
{
return fCStatus;
}
/*! \brief Reinitializes the object to the filesystem entry specified by the
given entry_ref struct.
\param ref the entry_ref
\return
- \c B_OK: The initialization was successful.
- \c B_BAD_VALUE: \c NULL \a ref.
- \c B_NAME_TOO_LONG: The pathname is longer than \c B_PATH_NAME_LENGTH.
- other error codes.
*/
status_t
BPath::SetTo(const entry_ref *ref)
{
Unset();
if (!ref)
return (fCStatus = B_BAD_VALUE);
char path[B_PATH_NAME_LENGTH];
status_t error = _kern_entry_ref_to_path(ref->device, ref->directory,
ref->name, path, sizeof(path));
if (error != B_OK)
return (fCStatus = error);
fCStatus = set_path(path); // the path is already normalized
return fCStatus;
}
/*! \brief Reinitializes the object to the specified filesystem entry.
\param entry the BEntry
\return
- \c B_OK: The initialization was successful.
- \c B_BAD_VALUE: \c NULL \a entry.
- \c B_NAME_TOO_LONG: The pathname is longer than \c B_PATH_NAME_LENGTH.
- other error codes.
*/
status_t
BPath::SetTo(const BEntry *entry)
{
Unset();
status_t error = (entry ? B_OK : B_BAD_VALUE);
entry_ref ref;
if (error == B_OK)
error = entry->GetRef(&ref);
if (error == B_OK)
error = SetTo(&ref);
fCStatus = error;
return error;
}
/*! \brief Reinitializes the object to the specified path or path and file
name combination.
\param path the path name
\param leaf the leaf name (may be \c NULL)
\param normalize boolean flag used to force normalization; normalization
may occur even if false (see \ref MustNormalize).
\return
- \c B_OK: The initialization was successful.
- \c B_BAD_VALUE: \c NULL \a path or absolute \a leaf.
- \c B_NAME_TOO_LONG: The pathname is longer than \c B_PATH_NAME_LENGTH.
- other error codes.
\note \code path.SetTo(path.Path(), "new leaf") \endcode is safe.
*/
status_t
BPath::SetTo(const char *path, const char *leaf, bool normalize)
{
status_t error = (path ? B_OK : B_BAD_VALUE);
if (error == B_OK && leaf && BPrivate::Storage::is_absolute_path(leaf))
error = B_BAD_VALUE;
char newPath[B_PATH_NAME_LENGTH];
if (error == B_OK) {
// we always normalize relative paths
normalize |= !BPrivate::Storage::is_absolute_path(path);
// build a new path from path and leaf
// copy path first
uint32 pathLen = strlen(path);
if (pathLen >= sizeof(newPath))
error = B_NAME_TOO_LONG;
if (error == B_OK)
strcpy(newPath, path);
// append leaf, if supplied
if (error == B_OK && leaf) {
bool needsSeparator = (pathLen > 0 && path[pathLen - 1] != '/');
uint32 wholeLen = pathLen + (needsSeparator ? 1 : 0)
+ strlen(leaf);
if (wholeLen >= sizeof(newPath))
error = B_NAME_TOO_LONG;
if (error == B_OK) {
if (needsSeparator) {
newPath[pathLen] = '/';
pathLen++;
}
strcpy(newPath + pathLen, leaf);
}
}
// check, if necessary to normalize
if (error == B_OK && !normalize) {
try {
normalize = normalize || MustNormalize(newPath);
} catch (BPath::EBadInput) {
error = B_BAD_VALUE;
}
}
// normalize the path, if necessary, otherwise just set it
if (error == B_OK) {
if (normalize) {
// create a BEntry and initialize us with this entry
BEntry entry;
error = entry.SetTo(newPath, false);
if (error == B_OK)
return SetTo(&entry);
} else
error = set_path(newPath);
}
}
// cleanup, if something went wrong
if (error != B_OK)
Unset();
fCStatus = error;
return error;
}
/*! \brief Reinitializes the object to the specified directory and relative
path combination.
\param dir Refers to the directory that provides the base component of the
pathname.
\param path the relative path name (may be \c NULL)
\param normalize boolean flag used to force normalization; normalization
may occur even if false (see \ref MustNormalize).
\return
- \c B_OK: The initialization was successful.
- \c B_BAD_VALUE: \c NULL \a dir or absolute \a path.
- \c B_NAME_TOO_LONG: The pathname is longer than \c B_PATH_NAME_LENGTH.
- other error codes.
*/
status_t
BPath::SetTo(const BDirectory *dir, const char *path, bool normalize)
{
status_t error = (dir && dir->InitCheck() == B_OK ? B_OK : B_BAD_VALUE);
// get the path of the BDirectory
BEntry entry;
if (error == B_OK)
error = dir->GetEntry(&entry);
BPath dirPath;
if (error == B_OK)
error = dirPath.SetTo(&entry);
// let the other version do the work
if (error == B_OK)
error = SetTo(dirPath.Path(), path, normalize);
if (error != B_OK)
Unset();
fCStatus = error;
return error;
}
/*! \brief Returns the object to an uninitialized state. The object frees any
resources it allocated and marks itself as uninitialized.
*/
void
BPath::Unset()
{
set_path(NULL);
fCStatus = B_NO_INIT;
}
/*! \brief Appends the given (relative) path to the end of the current path.
This call fails if the path is absolute or the object to which you're
appending is uninitialized.
\param path relative pathname to append to current path (may be \c NULL).
\param normalize boolean flag used to force normalization; normalization
may occur even if false (see \ref MustNormalize).
\return
- \c B_OK: The initialization was successful.
- \c B_BAD_VALUE: The object is not properly initialized.
- \c B_NAME_TOO_LONG: The pathname is longer than \c B_PATH_NAME_LENGTH.
- other error codes.
*/
status_t
BPath::Append(const char *path, bool normalize)
{
status_t error = (InitCheck() == B_OK ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = SetTo(Path(), path, normalize);
if (error != B_OK)
Unset();
fCStatus = error;
return error;
}
/*! Returns the object's complete path name.
\return
- the object's path name, or
- \c NULL, if it is not properly initialized.
*/
const char*
BPath::Path() const
{
return fName;
}
/*! Returns the leaf portion of the object's path name.
The leaf portion is defined as the string after the last \c '/'. For
the root path (\c "/") it is the empty string (\c "").
\return
- the leaf portion of the object's path name, or
- \c NULL, if it is not properly initialized.
*/
const char*
BPath::Leaf() const
{
const char *result = NULL;
if (InitCheck() == B_OK) {
result = fName + strlen(fName);
// There should be no need for the second condition, since we deal
// with absolute paths only and those contain at least one '/'.
// However, it doesn't harm.
while (*result != '/' && result > fName)
result--;
result++;
}
return result;
}
/*! \brief Calls the argument's SetTo() method with the name of the
object's parent directory.
No normalization is done.
\param path the BPath object to be initialized to the parent directory's
path name.
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL \a path.
- \c B_ENTRY_NOT_FOUND: The object represents \c "/".
- other error code returned by SetTo().
*/
status_t
BPath::GetParent(BPath *path) const
{
status_t error = (path ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK) {
int32 len = strlen(fName);
if (len == 1) // handle "/"
error = B_ENTRY_NOT_FOUND;
else {
char parentPath[B_PATH_NAME_LENGTH];
len--;
while (fName[len] != '/' && len > 0)
len--;
if (len == 0) // parent dir is "/"
len++;
memcpy(parentPath, fName, len);
parentPath[len] = 0;
error = path->SetTo(parentPath);
}
}
return error;
}
/*! Performs a simple (string-wise) comparison of paths.
No normalization takes place! Uninitialized BPath objects are considered
to be equal.
\param item the BPath object to be compared with
\return \c true, if the path names are equal, \c false otherwise.
*/
bool
BPath::operator==(const BPath &item) const
{
return (*this == item.Path());
}
/*! Performs a simple (string-wise) comparison of paths.
No normalization takes place!
\param path the path name to be compared with
\return \c true, if the path names are equal, \c false otherwise.
*/
bool
BPath::operator==(const char *path) const
{
return (InitCheck() != B_OK && path == NULL)
|| (fName != NULL && path != NULL && !strcmp(fName, path));
}
/*! Performs a simple (string-wise) comparison of paths.
No normalization takes place! Uninitialized BPath objects are considered
to be equal.
\param item the BPath object to be compared with
\return \c true, if the path names are not equal, \c false otherwise.
*/
bool
BPath::operator!=(const BPath &item) const
{
return !(*this == item);
}
/*! Performs a simple (string-wise) comparison of paths.
No normalization takes place!
\param path the path name to be compared with
\return \c true, if the path names are not equal, \c false otherwise.
*/
bool
BPath::operator!=(const char *path) const
{
return !(*this == path);
}
/*! Initializes the object to be a copy of the argument.
\param item the BPath object to be copied
\return \c *this
*/
BPath&
BPath::operator=(const BPath &item)
{
if (this != &item)
*this = item.Path();
return *this;
}
/*! Initializes the object to be a copy of the argument.
Has the same effect as \code SetTo(path) \endcode.
\param path the path name to be assigned to this object
\return \c *this
*/
BPath&
BPath::operator=(const char *path)
{
if (path == NULL)
Unset();
else
SetTo(path);
return *this;
}
// BFlattenable functionality
// that's the layout of a flattened entry_ref
struct flattened_entry_ref {
dev_t device;
ino_t directory;
char name[1];
};
// base size of a flattened entry ref
static const size_t flattened_entry_ref_size
= sizeof(dev_t) + sizeof(ino_t);
/*! Returns \c false.
Implements BFlattenable.
\return \c false
*/
bool
BPath::IsFixedSize() const
{
return false;
}
/*! Returns \c B_REF_TYPE.
Implements BFlattenable.
\return \c B_REF_TYPE
*/
type_code
BPath::TypeCode() const
{
return B_REF_TYPE;
}
/*! \brief Returns the size of the flattened entry_ref structure that
represents the pathname.
Implements BFlattenable.
\return the size needed for flattening.
*/
ssize_t
BPath::FlattenedSize() const
{
ssize_t size = flattened_entry_ref_size;
BEntry entry;
entry_ref ref;
if (InitCheck() == B_OK
&& entry.SetTo(Path()) == B_OK
&& entry.GetRef(&ref) == B_OK) {
size += strlen(ref.name) + 1;
}
return size;
}
/*! \brief Converts the object's pathname to an entry_ref and writes it into
buffer.
Implements BFlattenable.
\param buffer the buffer the data shall be stored in
\param size the size of \a buffer
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL buffer or the buffer is of insufficient size.
- other error codes.
\todo Reimplement for performance reasons: Don't call FlattenedSize().
*/
status_t
BPath::Flatten(void *buffer, ssize_t size) const
{
status_t error = (buffer ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
ssize_t flattenedSize = FlattenedSize();
if (flattenedSize < 0)
error = flattenedSize;
if (error == B_OK && size < flattenedSize)
error = B_BAD_VALUE;
if (error == B_OK) {
// convert the path to an entry_ref
BEntry entry;
entry_ref ref;
if (InitCheck() == B_OK && entry.SetTo(Path()) == B_OK)
entry.GetRef(&ref);
// store the entry_ref in the buffer
flattened_entry_ref &fref = *(flattened_entry_ref*)buffer;
fref.device = ref.device;
fref.directory = ref.directory;
if (ref.name)
strcpy(fref.name, ref.name);
}
}
return error;
}
/*! Returns \c true if code is \c B_REF_TYPE, and false otherwise.
Implements BFlattenable.
\param code the type code in question
\return \c true if code is \c B_REF_TYPE, and false otherwise.
*/
bool
BPath::AllowsTypeCode(type_code code) const
{
return (code == B_REF_TYPE);
}
/*! \brief Initializes the BPath with the flattened entry_ref data that's
found in the supplied buffer.
The type code must be \c B_REF_TYPE.
Implements BFlattenable.
\param code the type code of the flattened data
\param buf a pointer to the flattened data
\param size the number of bytes contained in \a buf
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL buffer or the buffer doesn't contain an
entry_ref.
- other error codes.
*/
status_t
BPath::Unflatten(type_code code, const void *buf, ssize_t size)
{
Unset();
status_t error = B_OK;
// check params
if (!(code == B_REF_TYPE && buf
&& size >= (ssize_t)flattened_entry_ref_size)) {
error = B_BAD_VALUE;
}
if (error == B_OK) {
if (size == (ssize_t)flattened_entry_ref_size) {
// already Unset();
} else {
// reconstruct the entry_ref from the buffer
const flattened_entry_ref &fref = *(const flattened_entry_ref*)buf;
BString name(fref.name, size - flattened_entry_ref_size);
entry_ref ref(fref.device, fref.directory, name.String());
error = SetTo(&ref);
}
}
if (error != B_OK)
fCStatus = error;
return error;
}
void BPath::_WarPath1() {}
void BPath::_WarPath2() {}
void BPath::_WarPath3() {}
/*! \brief Sets the supplied path.
The path is copied. If \c NULL, the object's path is set to NULL as well.
The object's old path is deleted.
\param path the path to be set
\return
- \c B_OK: Everything went fine.
- \c B_NO_MEMORY: Insufficient memory.
*/
status_t
BPath::set_path(const char *path)
{
status_t error = B_OK;
const char *oldPath = fName;
// set the new path
if (path) {
fName = new(nothrow) char[strlen(path) + 1];
if (fName)
strcpy(fName, path);
else
error = B_NO_MEMORY;
} else
fName = NULL;
// delete the old one
delete[] oldPath;
return error;
}
/*! \brief Checks a path to see if normalization is required.
The following items require normalization:
- Relative pathnames (after concatenation; e.g. "boot/ltj")
- The presence of "." or ".." ("/boot/ltj/../ltj/./gwar")
- Redundant slashes ("/boot//ltj")
- A trailing slash ("/boot/ltj/")
\return
- \c true: \a path requires normalization
- \c false: \a path does not require normalization
\exception BPath::EBadInput : \a path is \c NULL or an empty string.
*/
bool
BPath::MustNormalize(const char *path)
{
// Check for useless input
if (path == NULL || path[0] == 0)
throw BPath::EBadInput();
int len = strlen(path);
/* Look for anything in the string that forces us to normalize:
+ No leading /
+ any occurence of /./ or /../ or //, or a trailing /. or /..
+ a trailing /
*/;
if (path[0] != '/')
return true; // not "/*"
else if (len == 1)
return false; // "/"
else if (len > 1 && path[len-1] == '/')
return true; // "*/"
else {
enum ParseState {
NoMatch,
InitialSlash,
OneDot,
TwoDots
} state = NoMatch;
for (int i = 0; path[i] != 0; i++) {
switch (state) {
case NoMatch:
if (path[i] == '/')
state = InitialSlash;
break;
case InitialSlash:
if (path[i] == '/')
return true; // "*//*"
else if (path[i] == '.')
state = OneDot;
else
state = NoMatch;
break;
case OneDot:
if (path[i] == '/')
return true; // "*/./*"
else if (path[i] == '.')
state = TwoDots;
else
state = NoMatch;
break;
case TwoDots:
if (path[i] == '/')
return true; // "*/../*"
else
state = NoMatch;
break;
}
}
// If we hit the end of the string while in either
// of these two states, there was a trailing /. or /..
if (state == OneDot || state == TwoDots)
return true;
else
return false;
}
}
/*! \class BPath::EBadInput
\brief Internal exception class thrown by BPath::MustNormalize() when given
invalid input.
*/
/*!
\var char *BPath::fName
\brief Pointer to the object's path name string.
*/
/*!
\var status_t BPath::fCStatus
\brief The object's initialization status.
*/

File diff suppressed because it is too large Load Diff

View File

@ -1,194 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file ResourcesItem.cpp
ResourceItem implementation.
*/
#include "ResourceItem.h"
#include <stdio.h>
#include <string.h>
#include <DataIO.h>
namespace BPrivate {
namespace Storage {
// constructor
ResourceItem::ResourceItem()
: BMallocIO(),
fOffset(0),
fInitialSize(0),
fType(0),
fID(0),
fName(),
fIsLoaded(false),
fIsModified(false)
{
SetBlockSize(1);
}
// destructor
ResourceItem::~ResourceItem()
{
}
// WriteAt
ssize_t
ResourceItem::WriteAt(off_t pos, const void *buffer, size_t size)
{
ssize_t result = BMallocIO::WriteAt(pos, buffer, size);
if (result >= 0)
SetModified(true);
return result;
}
// SetSize
status_t
ResourceItem::SetSize(off_t size)
{
status_t error = BMallocIO::SetSize(size);
if (error == B_OK)
SetModified(true);
return error;
}
// SetLocation
void
ResourceItem::SetLocation(int32 offset, size_t initialSize)
{
SetOffset(offset);
fInitialSize = initialSize;
}
// SetIdentity
void
ResourceItem::SetIdentity(type_code type, int32 id, const char *name)
{
fType = type;
fID = id;
fName = name;
}
// SetOffset
void
ResourceItem::SetOffset(int32 offset)
{
fOffset = offset;
}
// Offset
int32
ResourceItem::Offset() const
{
return fOffset;
}
// InitialSize
size_t
ResourceItem::InitialSize() const
{
return fInitialSize;
}
// DataSize
size_t
ResourceItem::DataSize() const
{
if (IsModified())
return BufferLength();
return fInitialSize;
}
// SetType
void
ResourceItem::SetType(type_code type)
{
fType = type;
}
// Type
type_code
ResourceItem::Type() const
{
return fType;
}
// SetID
void
ResourceItem::SetID(int32 id)
{
fID = id;
}
// ID
int32
ResourceItem::ID() const
{
return fID;
}
// SetName
void
ResourceItem::SetName(const char *name)
{
fName = name;
}
// Name
const char *
ResourceItem::Name() const
{
return fName.String();
}
// Data
void *
ResourceItem::Data() const
{
// Since MallocIO may have a NULL buffer, if the data size is 0,
// we return a pointer to ourselves in this case. This ensures, that
// the resource item still can be uniquely identified by its data pointer.
if (DataSize() == 0)
return const_cast<ResourceItem*>(this);
return const_cast<void*>(Buffer());
}
// SetLoaded
void
ResourceItem::SetLoaded(bool loaded)
{
fIsLoaded = loaded;
}
// IsLoaded
bool
ResourceItem::IsLoaded() const
{
return (BufferLength() > 0 || fIsLoaded);
}
// SetModified
void
ResourceItem::SetModified(bool modified)
{
fIsModified = modified;
}
// IsModified
bool
ResourceItem::IsModified() const
{
return fIsModified;
}
}; // namespace Storage
}; // namespace BPrivate

View File

@ -1,405 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file ResourceStrings.cpp
BResourceStrings implementation.
*/
#include <ResourceStrings.h>
#include <new>
#include <stdlib.h>
#include <string.h>
#include <Entry.h>
#include <File.h>
#include <Resources.h>
#include <String.h>
#include <AppMisc.h>
using namespace std;
// constructor
/*! \brief Creates an object initialized to the application's string resources.
*/
BResourceStrings::BResourceStrings()
: _string_lock(),
_init_error(),
fFileRef(),
fResources(NULL),
fHashTable(NULL),
fHashTableSize(0),
fStringCount(0)
{
SetStringFile(NULL);
}
// constructor
/*! \brief Creates an object initialized to the string resources of the
file referred to by the supplied entry_ref.
\param ref the entry_ref referring to the resource file
*/
BResourceStrings::BResourceStrings(const entry_ref &ref)
: _string_lock(),
_init_error(),
fFileRef(),
fResources(NULL),
fHashTable(NULL),
fHashTableSize(0),
fStringCount(0)
{
SetStringFile(&ref);
}
// destructor
/*! \brief Frees all resources associated with the BResourceStrings object.
*/
BResourceStrings::~BResourceStrings()
{
_string_lock.Lock();
_Cleanup();
}
// InitCheck
/*! \brief Returns the status of the last initialization via contructor or
SetStringFile().
\return \c B_OK, if the object is properly initialized, an error code
otherwise.
*/
status_t
BResourceStrings::InitCheck()
{
return _init_error;
}
// NewString
/*! \brief Finds and returns a copy of the string identified by the supplied
ID.
The caller is responsible for deleting the returned BString object.
\param id the ID of the requested string
\return
- A string object containing the requested string,
- \c NULL, if the object is not properly initialized or there is no string
with ID \a id.
*/
BString *
BResourceStrings::NewString(int32 id)
{
// _string_lock.Lock();
BString *result = NULL;
if (const char *str = FindString(id))
result = new(nothrow) BString(str);
// _string_lock.Unlock();
return result;
}
// FindString
/*! \brief Finds and returns the string identified by the supplied ID.
The caller must not free the returned string. It belongs to the
BResourceStrings object and is valid until the object is destroyed or set
to another file.
\param id the ID of the requested string
\return
- The requested string,
- \c NULL, if the object is not properly initialized or there is no string
with ID \a id.
*/
const char *
BResourceStrings::FindString(int32 id)
{
_string_lock.Lock();
const char *result = NULL;
if (InitCheck() == B_OK) {
if (_string_id_hash *entry = _FindString(id))
result = entry->data;
}
_string_lock.Unlock();
return result;
}
// SetStringFile
/*! \brief Re-initialized the BResourceStrings object to the file referred to
by the supplied entry_ref.
If the supplied entry_ref is \c NULL, the object is initialized to the
application file.
\param ref the entry_ref referring to the resource file
*/
status_t
BResourceStrings::SetStringFile(const entry_ref *ref)
{
_string_lock.Lock();
// cleanup
_Cleanup();
// get the ref (if NULL, take the application)
status_t error = B_OK;
entry_ref fileRef;
if (ref) {
fileRef = *ref;
fFileRef = *ref;
} else
error = BPrivate::get_app_ref(&fileRef);
// get the BResources
if (error == B_OK) {
BFile file(&fileRef, B_READ_ONLY);
error = file.InitCheck();
if (error == B_OK) {
fResources = new(nothrow) BResources;
if (fResources)
error = fResources->SetTo(&file);
else
error = B_NO_MEMORY;
}
}
// read the strings
if (error == B_OK) {
// count them first
fStringCount = 0;
int32 id;
const char *name;
size_t length;
while (fResources->GetResourceInfo(RESOURCE_TYPE, fStringCount, &id,
&name, &length)) {
fStringCount++;
}
// allocate a hash table with a nice size
// I don't have a heuristic at hand, so let's simply take the count.
error = _Rehash(fStringCount);
// load the resources
for (int32 i = 0; error == B_OK && i < fStringCount; i++) {
if (!fResources->GetResourceInfo(RESOURCE_TYPE, i, &id, &name,
&length)) {
error = B_ERROR;
}
if (error == B_OK) {
const void *data
= fResources->LoadResource(RESOURCE_TYPE, id, &length);
if (data) {
_string_id_hash *entry = NULL;
if (length == 0)
entry = _AddString(NULL, id, false);
else
entry = _AddString((char*)data, id, false);
if (!entry)
error = B_ERROR;
} else
error = B_ERROR;
}
}
}
// if something went wrong, cleanup the mess
if (error != B_OK)
_Cleanup();
_init_error = error;
_string_lock.Unlock();
return error;
}
// GetStringFile
/*! \brief Returns an entry_ref referring to the resource file, the object is
currently initialized to.
\param outRef a pointer to an entry_ref variable to be initialized to the
requested entry_ref
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL \a outRef.
- other error codes
*/
status_t
BResourceStrings::GetStringFile(entry_ref *outRef)
{
status_t error = (outRef ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK) {
if (fFileRef == entry_ref())
error = B_ENTRY_NOT_FOUND;
else
*outRef = fFileRef;
}
return error;
}
// _Cleanup
/*! \brief Frees all resources associated with this object and sets all
member variables to harmless values.
*/
void
BResourceStrings::_Cleanup()
{
// _string_lock.Lock();
_MakeEmpty();
delete[] fHashTable;
fHashTable = NULL;
delete fResources;
fResources = NULL;
fFileRef = entry_ref();
fHashTableSize = 0;
fStringCount = 0;
_init_error = B_OK;
// _string_lock.Unlock();
}
// _MakeEmpty
/*! \brief Empties the id->string hash table.
*/
void
BResourceStrings::_MakeEmpty()
{
if (fHashTable) {
for (int32 i = 0; i < fHashTableSize; i++) {
while (_string_id_hash *entry = fHashTable[i]) {
fHashTable[i] = entry->next;
delete entry;
}
}
fStringCount = 0;
}
}
// _Rehash
/*! \brief Resizes the id->string hash table to the supplied size.
\param newSize the new hash table size
\return
- \c B_OK: Everything went fine.
- \c B_NO_MEMORY: Insuffient memory.
*/
status_t
BResourceStrings::_Rehash(int32 newSize)
{
status_t error = B_OK;
if (newSize > 0 && newSize != fHashTableSize) {
// alloc a new table and fill it with NULL
_string_id_hash **newHashTable
= new(nothrow) _string_id_hash*[newSize];
if (newHashTable) {
memset(newHashTable, 0, sizeof(_string_id_hash*) * newSize);
// move the entries to the new table
if (fHashTable && fHashTableSize > 0 && fStringCount > 0) {
for (int32 i = 0; i < fHashTableSize; i++) {
while (_string_id_hash *entry = fHashTable[i]) {
fHashTable[i] = entry->next;
int32 newPos = entry->id % newSize;
entry->next = newHashTable[newPos];
newHashTable[newPos] = entry;
}
}
}
// set the new table
delete[] fHashTable;
fHashTable = newHashTable;
fHashTableSize = newSize;
} else
error = B_NO_MEMORY;
}
return error;
}
// _AddString
/*! \brief Adds an entry to the id->string hash table.
If there is already a string with the given ID, it will be replaced.
\param str the string
\param id the id of the string
\param wasMalloced if \c true, the object will be responsible for
free()ing the supplied string
\return the hash table entry or \c NULL, if something went wrong
*/
BResourceStrings::_string_id_hash *
BResourceStrings::_AddString(char *str, int32 id, bool wasMalloced)
{
_string_id_hash *entry = NULL;
if (fHashTable && fHashTableSize > 0)
entry = new(nothrow) _string_id_hash;
if (entry) {
entry->assign_string(str, false);
entry->id = id;
entry->data_alloced = wasMalloced;
int32 pos = id % fHashTableSize;
entry->next = fHashTable[pos];
fHashTable[pos] = entry;
}
return entry;
}
// _FindString
/*! \brief Returns the hash table entry for a given ID.
\param id the ID
\return the hash table entry or \c NULL, if there is no entry with this ID
*/
BResourceStrings::_string_id_hash *
BResourceStrings::_FindString(int32 id)
{
_string_id_hash *entry = NULL;
if (fHashTable && fHashTableSize > 0) {
int32 pos = id % fHashTableSize;
entry = fHashTable[pos];
while (entry != NULL && entry->id != id)
entry = entry->next;
}
return entry;
}
// FBC
status_t BResourceStrings::_Reserved_ResourceStrings_0(void *) { return 0; }
status_t BResourceStrings::_Reserved_ResourceStrings_1(void *) { return 0; }
status_t BResourceStrings::_Reserved_ResourceStrings_2(void *) { return 0; }
status_t BResourceStrings::_Reserved_ResourceStrings_3(void *) { return 0; }
status_t BResourceStrings::_Reserved_ResourceStrings_4(void *) { return 0; }
status_t BResourceStrings::_Reserved_ResourceStrings_5(void *) { return 0; }
// _string_id_hash
// constructor
/*! \brief Creates an uninitialized hash table entry.
*/
BResourceStrings::_string_id_hash::_string_id_hash()
: next(NULL),
id(0),
data(NULL),
data_alloced(false)
{
}
// destructor
/*! \brief Frees all resources associated with this object.
Only if \c data_alloced is \c true, the string will be free()d.
*/
BResourceStrings::_string_id_hash::~_string_id_hash()
{
if (data_alloced)
free(data);
}
// assign_string
/*! \brief Sets the string of the hash table entry.
\param str the string
\param makeCopy If \c true, the supplied string is copied and the copy
will be freed on destruction. If \c false, the entry points to the
supplied string. It will not be freed() on destruction.
*/
void
BResourceStrings::_string_id_hash::assign_string(const char *str,
bool makeCopy)
{
if (data_alloced)
free(data);
data = NULL;
data_alloced = false;
if (str) {
if (makeCopy) {
data = strdup(str);
data_alloced = true;
} else
data = const_cast<char*>(str);
}
}

View File

@ -1,854 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the OpenBeOS distribution and is covered
// by the OpenBeOS license.
//---------------------------------------------------------------------
/*!
\file Resources.cpp
BResources implementation.
BResources delegates most of the work to ResourcesContainer and
ResourceFile. The first one manages a collections of ResourceItem's,
the actual resources, whereas the latter provides the file I/O
functionality.
An InitCheck() method is not needed, since a BResources object will
never be invalid. It always serves as a resources container, even if
it is not associated with a file. It is always possible to WriteTo()
the resources BResources contains to a file (a valid one of course).
*/
#include <Resources.h>
#include <new>
#include <stdio.h>
#include <stdlib.h>
#include "ResourceFile.h"
#include "ResourceItem.h"
#include "ResourcesContainer.h"
using namespace BPrivate::Storage;
using namespace std;
// debugging
//#define DBG(x) x
#define DBG(x)
#define OUT printf
// constructor
/*! \brief Creates an unitialized BResources object.
*/
BResources::BResources()
: fFile(),
fContainer(NULL),
fResourceFile(NULL),
fReadOnly(false)
{
fContainer = new(nothrow) ResourcesContainer;
}
// constructor
/*! \brief Creates a BResources object that represents the resources of the
supplied file.
If the \a clobber argument is \c true, the data of the file are erased
and it is turned into an empty resource file. Otherwise \a file
must refer either to a resource file or to an executable (ELF or PEF
binary). If the file has been opened \c B_READ_ONLY, only read access
to its resources is possible.
The BResources object makes a copy of \a file, that is the caller remains
owner of the BFile object.
\param file the file
\param clobber if \c true, the \a file is truncated to size 0
*/
BResources::BResources(const BFile *file, bool clobber)
: fFile(),
fContainer(NULL),
fResourceFile(NULL),
fReadOnly(false)
{
fContainer = new(nothrow) ResourcesContainer;
SetTo(file, clobber);
}
// destructor
/*! \brief Frees all resources associated with this object
Calls Sync() before doing so to make sure that the changes are written
back to the file.
*/
BResources::~BResources()
{
Unset();
delete fContainer;
}
// SetTo
/*! \brief Re-initialized the BResources object to represent the resources of
the supplied file.
What happens, if \a clobber is \c true, depends on the type of the file.
If the file is capable of containing resources, that is, is a resource
file or an executable (ELF or PEF), its resources are removed. Otherwise
the file's data are erased and it is turned into an empty resource file.
If \a clobber is \c false, \a file must refer to a file that is capable
of containing resources.
If the file has been opened \c B_READ_ONLY, only read access
to its resources is possible.
The BResources object makes a copy of \a file, that is the caller remains
owner of the BFile object.
\param file the file
\param clobber if \c true, the \a file is truncated to size 0
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL or uninitialized \a file.
- \c B_ERROR: Failed to initialize the object (for whatever reason).
*/
status_t
BResources::SetTo(const BFile *file, bool clobber)
{
Unset();
status_t error = B_OK;
if (file) {
error = file->InitCheck();
if (error == B_OK) {
fFile = *file;
error = fFile.InitCheck();
}
if (error == B_OK) {
fReadOnly = !fFile.IsWritable();
fResourceFile = new(nothrow) ResourceFile;
if (fResourceFile)
error = fResourceFile->SetTo(&fFile, clobber);
else
error = B_NO_MEMORY;
}
if (error == B_OK) {
if (fContainer)
error = fResourceFile->InitContainer(*fContainer);
else
error = B_NO_MEMORY;
}
}
if (error != B_OK) {
delete fResourceFile;
fResourceFile = NULL;
if (fContainer)
fContainer->MakeEmpty();
}
return error;
}
// Unset
/*! \brief Returns the BResources object to an uninitialized state.
If the object represented resources that had been modified, the data are
written back to the file.
\note This method extends the BeOS R5 API.
*/
void
BResources::Unset()
{
if (fContainer && fContainer->IsModified())
Sync();
delete fResourceFile;
fResourceFile = NULL;
fFile.Unset();
if (fContainer)
fContainer->MakeEmpty();
else
fContainer = new(nothrow) ResourcesContainer;
fReadOnly = false;
}
// InitCheck
/*! Returns the current initialization status.
Unlike other Storage Kit classes a BResources object is always properly
initialized, unless it couldn't allocate memory for some important
internal structures. Thus even after a call to SetTo() that reported an
error, InitCheck() is likely to return \c B_OK.
\return
- \c B_OK, if the objects is properly initialized,
- \c B_NO_MEMORY otherwise.
\note This method extends the BeOS R5 API.
*/
status_t
BResources::InitCheck() const
{
return (fContainer ? B_OK : B_NO_MEMORY);
}
// File
/*! \brief Returns a reference to the BResources' BFile object.
\return a reference to the object's BFile.
*/
const BFile &
BResources::File() const
{
return fFile;
}
// LoadResource
/*! \brief Loads a resource identified by type and ID into memory.
A resource is loaded into memory only once. A second call with the same
parameters will result in the same pointer. The BResources object is the
owner of the allocated memory and the pointer to it will be valid until
the object is destroyed or the resource is removed or modified.
\param type the type of the resource to be loaded
\param id the ID of the resource to be loaded
\param outSize a pointer to a variable into which the size of the resource
shall be written
\return A pointer to the resource data, if everything went fine, or
\c NULL, if the file does not have a resource that matchs the
parameters or an error occured.
*/
const void *
BResources::LoadResource(type_code type, int32 id, size_t *outSize)
{
// find the resource
status_t error = InitCheck();
ResourceItem *resource = NULL;
if (error == B_OK) {
resource = fContainer->ResourceAt(fContainer->IndexOf(type, id));
if (!resource)
error = B_ENTRY_NOT_FOUND;
}
// load it, if necessary
if (error == B_OK && !resource->IsLoaded() && fResourceFile)
error = fResourceFile->ReadResource(*resource);
// return the result
const void *result = NULL;
if (error == B_OK) {
result = resource->Data();
if (outSize)
*outSize = resource->DataSize();
}
return result;
}
// LoadResource
/*! \brief Loads a resource identified by type and name into memory.
A resource is loaded into memory only once. A second call with the same
parameters will result in the same pointer. The BResources object is the
owner of the allocated memory and the pointer to it will be valid until
the object is destroyed or the resource is removed or modified.
\param type the type of the resource to be loaded
\param name the name of the resource to be loaded
\param outSize a pointer to a variable into which the size of the resource
shall be written
\return A pointer to the resource data, if everything went fine, or
\c NULL, if the file does not have a resource that matches the
parameters or an error occured.
\note Since a type and name pair may not identify a resource uniquely,
this method always returns the first resource that matches the
parameters, that is the one with the least index.
*/
const void *
BResources::LoadResource(type_code type, const char *name, size_t *outSize)
{
// find the resource
status_t error = InitCheck();
ResourceItem *resource = NULL;
if (error == B_OK) {
resource = fContainer->ResourceAt(fContainer->IndexOf(type, name));
if (!resource)
error = B_ENTRY_NOT_FOUND;
}
// load it, if necessary
if (error == B_OK && !resource->IsLoaded() && fResourceFile)
error = fResourceFile->ReadResource(*resource);
// return the result
const void *result = NULL;
if (error == B_OK) {
result = resource->Data();
if (outSize)
*outSize = resource->DataSize();
}
return result;
}
// PreloadResourceType
/*! \brief Loads all resources of a certain type into memory.
For performance reasons it might be useful to do that. If \a type is
0, all resources are loaded.
\param type of the resources to be loaded
\return
- \c B_OK: Everything went fine.
- \c B_BAD_FILE: The resource map is empty???
- The negative of the number of errors occured.
*/
status_t
BResources::PreloadResourceType(type_code type)
{
status_t error = InitCheck();
if (error == B_OK && fResourceFile) {
if (type == 0)
error = fResourceFile->ReadResources(*fContainer);
else {
int32 count = fContainer->CountResources();
int32 errorCount = 0;
for (int32 i = 0; i < count; i++) {
ResourceItem *resource = fContainer->ResourceAt(i);
if (resource->Type() == type) {
if (fResourceFile->ReadResource(*resource) != B_OK)
errorCount++;
}
}
error = -errorCount;
}
}
return error;
}
// Sync
/*! \brief Writes all changes to the resources to the file.
Since AddResource() and RemoveResource() may change the resources only in
memory, this method can be used to make sure, that all changes are
actually written to the file.
The BResources object's destructor calls Sync() before cleaning up.
\return
- \c B_OK: Everything went fine.
- \c B_BAD_FILE: The resource map is empty???
- \c B_NOT_ALLOWED: The file is opened read only.
- \c B_FILE_ERROR: A file error occured.
- \c B_IO_ERROR: An error occured while writing the resources.
\note When a resource is written to the file, its data are converted
to the endianess of the file, and when reading a resource, the
data are converted to the host's endianess. This does of course
only work for known types, i.e. those that swap_data() is able to
cope with.
*/
status_t
BResources::Sync()
{
status_t error = InitCheck();
if (error == B_OK)
error = fFile.InitCheck();
if (error == B_OK) {
if (fReadOnly)
error = B_NOT_ALLOWED;
else if (!fResourceFile)
error = B_FILE_ERROR;
}
if (error == B_OK)
error = fResourceFile->ReadResources(*fContainer);
if (error == B_OK)
error = fResourceFile->WriteResources(*fContainer);
return error;
}
// MergeFrom
/*! \brief Adds the resources of the supplied file to this file's resources.
\param fromFile the file whose resources shall be copied
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL \a fromFile.
- \c B_BAD_FILE: The resource map is empty???
- \c B_FILE_ERROR: A file error occured.
- \c B_IO_ERROR: An error occured while writing the resources.
*/
status_t
BResources::MergeFrom(BFile *fromFile)
{
status_t error = (fromFile ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK) {
ResourceFile resourceFile;
error = resourceFile.SetTo(fromFile);
ResourcesContainer container;
if (error == B_OK)
error = resourceFile.InitContainer(container);
if (error == B_OK)
error = resourceFile.ReadResources(container);
if (error == B_OK)
fContainer->AssimilateResources(container);
}
return error;
}
// WriteTo
/*! \brief Writes the resources to a new file.
The resources formerly contained in the target file (if any) are erased.
When the method returns, the BResources object refers to the new file.
\param file the file the resources shall be written to.
\return
- \c B_OK: Everything went fine.
- a specific error code.
\note If the resources have been modified, but not Sync()ed, the old file
remains unmodified.
*/
status_t
BResources::WriteTo(BFile *file)
{
status_t error = (file ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
// make sure, that all resources are loaded
if (error == B_OK && fResourceFile) {
error = fResourceFile->ReadResources(*fContainer);
fResourceFile->Unset();
}
// set the new file, but keep the old container
if (error == B_OK) {
ResourcesContainer *container = fContainer;
fContainer = new(nothrow) ResourcesContainer;
if (fContainer) {
error = SetTo(file, false);
delete fContainer;
} else
error = B_NO_MEMORY;
fContainer = container;
}
// write the resources
if (error == B_OK && fResourceFile)
error = fResourceFile->WriteResources(*fContainer);
return error;
}
// AddResource
/*! \brief Adds a new resource to the file.
If a resource with the same type and ID does already exist, it is
replaced. The caller keeps the ownership of the supplied chunk of memory
containing the resource data.
Supplying an empty name (\c "") is equivalent to supplying a \c NULL name.
\param type the type of the resource
\param id the ID of the resource
\param data the resource data
\param length the size of the data in bytes
\param name the name of the resource (may be \c NULL)
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL \a data
- \c B_NOT_ALLOWED: The file is opened read only.
- \c B_FILE_ERROR: A file error occured.
- \c B_NO_MEMORY: Not enough memory for that operation.
*/
status_t
BResources::AddResource(type_code type, int32 id, const void *data,
size_t length, const char *name)
{
status_t error = (data ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK)
error = (fReadOnly ? B_NOT_ALLOWED : B_OK);
if (error == B_OK) {
ResourceItem *item = new(nothrow) ResourceItem;
if (!item)
error = B_NO_MEMORY;
if (error == B_OK) {
item->SetIdentity(type, id, name);
ssize_t written = item->WriteAt(0, data, length);
if (written < 0)
error = written;
else if (written != (ssize_t)length)
error = B_ERROR;
}
if (error == B_OK) {
if (!fContainer->AddResource(item))
error = B_NO_MEMORY;
}
if (error != B_OK)
delete item;
}
return error;
}
// HasResource
/*! \brief Returns whether the file contains a resource with a certain
type and ID.
\param type the resource type
\param id the ID of the resource
\return \c true, if the file contains a matching resource, \false otherwise
*/
bool
BResources::HasResource(type_code type, int32 id)
{
return (InitCheck() == B_OK && fContainer->IndexOf(type, id) >= 0);
}
// HasResource
/*! \brief Returns whether the file contains a resource with a certain
type and name.
\param type the resource type
\param name the name of the resource
\return \c true, if the file contains a matching resource, \false otherwise
*/
bool
BResources::HasResource(type_code type, const char *name)
{
return (InitCheck() == B_OK && fContainer->IndexOf(type, name) >= 0);
}
// GetResourceInfo
/*! \brief Returns information about a resource identified by an index.
\param byIndex the index of the resource in the file
\param typeFound a pointer to a variable the type of the found resource
shall be written into
\param idFound a pointer to a variable the ID of the found resource
shall be written into
\param nameFound a pointer to a variable the name pointer of the found
resource shall be written into
\param lengthFound a pointer to a variable the data size of the found
resource shall be written into
\return \c true, if a matching resource could be found, false otherwise
*/
bool
BResources::GetResourceInfo(int32 byIndex, type_code *typeFound,
int32 *idFound, const char **nameFound,
size_t *lengthFound)
{
ResourceItem *item = NULL;
if (InitCheck() == B_OK)
item = fContainer->ResourceAt(byIndex);
if (item) {
if (typeFound)
*typeFound = item->Type();
if (idFound)
*idFound = item->ID();
if (nameFound)
*nameFound = item->Name();
if (lengthFound)
*lengthFound = item->DataSize();
}
return item;
}
// GetResourceInfo
/*! \brief Returns information about a resource identified by a type and an
index.
\param byType the resource type
\param andIndex the index into a array of resources of type \a byType
\param idFound a pointer to a variable the ID of the found resource
shall be written into
\param nameFound a pointer to a variable the name pointer of the found
resource shall be written into
\param lengthFound a pointer to a variable the data size of the found
resource shall be written into
\return \c true, if a matching resource could be found, false otherwise
*/
bool
BResources::GetResourceInfo(type_code byType, int32 andIndex, int32 *idFound,
const char **nameFound, size_t *lengthFound)
{
ResourceItem *item = NULL;
if (InitCheck() == B_OK) {
item = fContainer->ResourceAt(fContainer->IndexOfType(byType,
andIndex));
}
if (item) {
if (idFound)
*idFound = item->ID();
if (nameFound)
*nameFound = item->Name();
if (lengthFound)
*lengthFound = item->DataSize();
}
return item;
}
// GetResourceInfo
/*! \brief Returns information about a resource identified by a type and an ID.
\param byType the resource type
\param andID the resource ID
\param nameFound a pointer to a variable the name pointer of the found
resource shall be written into
\param lengthFound a pointer to a variable the data size of the found
resource shall be written into
\return \c true, if a matching resource could be found, false otherwise
*/
bool
BResources::GetResourceInfo(type_code byType, int32 andID,
const char **nameFound, size_t *lengthFound)
{
ResourceItem *item = NULL;
if (InitCheck() == B_OK)
item = fContainer->ResourceAt(fContainer->IndexOf(byType, andID));
if (item) {
if (nameFound)
*nameFound = item->Name();
if (lengthFound)
*lengthFound = item->DataSize();
}
return item;
}
// GetResourceInfo
/*! \brief Returns information about a resource identified by a type and a
name.
\param byType the resource type
\param andName the resource name
\param idFound a pointer to a variable the ID of the found resource
shall be written into
\param lengthFound a pointer to a variable the data size of the found
resource shall be written into
\return \c true, if a matching resource could be found, false otherwise
*/
bool
BResources::GetResourceInfo(type_code byType, const char *andName,
int32 *idFound, size_t *lengthFound)
{
ResourceItem *item = NULL;
if (InitCheck() == B_OK)
item = fContainer->ResourceAt(fContainer->IndexOf(byType, andName));
if (item) {
if (idFound)
*idFound = item->ID();
if (lengthFound)
*lengthFound = item->DataSize();
}
return item;
}
// GetResourceInfo
/*! \brief Returns information about a resource identified by a data pointer.
\param byPointer the pointer to the resource data (formely returned by
LoadResource())
\param typeFound a pointer to a variable the type of the found resource
shall be written into
\param idFound a pointer to a variable the ID of the found resource
shall be written into
\param lengthFound a pointer to a variable the data size of the found
resource shall be written into
\param nameFound a pointer to a variable the name pointer of the found
resource shall be written into
\return \c true, if a matching resource could be found, false otherwise
*/
bool
BResources::GetResourceInfo(const void *byPointer, type_code *typeFound,
int32 *idFound, size_t *lengthFound,
const char **nameFound)
{
ResourceItem *item = NULL;
if (InitCheck() == B_OK)
item = fContainer->ResourceAt(fContainer->IndexOf(byPointer));
if (item) {
if (typeFound)
*typeFound = item->Type();
if (idFound)
*idFound = item->ID();
if (nameFound)
*nameFound = item->Name();
if (lengthFound)
*lengthFound = item->DataSize();
}
return item;
}
// RemoveResource
/*! \brief Removes a resource identified by its data pointer.
\param resource the pointer to the resource data (formely returned by
LoadResource())
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \c NULL or invalid (not pointing to any resource data of
this file) \a resource.
- \c B_NOT_ALLOWED: The file is opened read only.
- \c B_FILE_ERROR: A file error occured.
- \c B_ERROR: An error occured while removing the resource.
*/
status_t
BResources::RemoveResource(const void *resource)
{
status_t error = (resource ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK)
error = (fReadOnly ? B_NOT_ALLOWED : B_OK);
if (error == B_OK) {
ResourceItem *item
= fContainer->RemoveResource(fContainer->IndexOf(resource));
if (item)
delete item;
else
error = B_BAD_VALUE;
}
return error;
}
// RemoveResource
/*! \brief Removes a resource identified by type and ID.
\param type the type of the resource
\param id the ID of the resource
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: No such resource.
- \c B_NOT_ALLOWED: The file is opened read only.
- \c B_FILE_ERROR: A file error occured.
- \c B_ERROR: An error occured while removing the resource.
*/
status_t
BResources::RemoveResource(type_code type, int32 id)
{
status_t error = InitCheck();
if (error == B_OK)
error = (fReadOnly ? B_NOT_ALLOWED : B_OK);
if (error == B_OK) {
ResourceItem *item
= fContainer->RemoveResource(fContainer->IndexOf(type, id));
if (item)
delete item;
else
error = B_BAD_VALUE;
}
return error;
}
// deprecated
// WriteResource
/*! \brief Writes data into an existing resource.
If writing the data would exceed the bounds of the resource, it is
enlarged respectively. If \a offset is past the end of the resource,
padding with unspecified data is inserted.
\param type the type of the resource
\param id the ID of the resource
\param data the data to be written
\param offset the byte offset relative to the beginning of the resource at
which the data shall be written
\param length the size of the data to be written
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \a type and \a id do not identify an existing resource or
\c NULL \a data.
- \c B_NO_MEMORY: Not enough memory for this operation.
- other error codes.
\deprecated Always use AddResource().
*/
status_t
BResources::WriteResource(type_code type, int32 id, const void *data,
off_t offset, size_t length)
{
status_t error = (data && offset >= 0 ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
if (error == B_OK)
error = (fReadOnly ? B_NOT_ALLOWED : B_OK);
ResourceItem *item = NULL;
if (error == B_OK) {
item = fContainer->ResourceAt(fContainer->IndexOf(type, id));
if (!item)
error = B_BAD_VALUE;
}
if (error == B_OK && fResourceFile)
error = fResourceFile->ReadResource(*item);
if (error == B_OK) {
if (item) {
ssize_t written = item->WriteAt(offset, data, length);
if (written < 0)
error = written;
else if (written != (ssize_t)length)
error = B_ERROR;
}
}
return error;
}
// ReadResource
/*! \brief Reads data from an existing resource.
If more data than existing are requested, this method does not fail. It
will then read only the existing data. As a consequence an offset past
the end of the resource will not cause the method to fail, but no data
will be read at all.
\param type the type of the resource
\param id the ID of the resource
\param data a pointer to a buffer into which the data shall be read
\param offset the byte offset relative to the beginning of the resource
from which the data shall be read
\param length the size of the data to be read
\return
- \c B_OK: Everything went fine.
- \c B_BAD_VALUE: \a type and \a id do not identify an existing resource or
\c NULL \a data.
- \c B_NO_MEMORY: Not enough memory for this operation.
- other error codes.
\deprecated Use LoadResource() only.
*/
status_t
BResources::ReadResource(type_code type, int32 id, void *data, off_t offset,
size_t length)
{
status_t error = (data && offset >= 0 ? B_OK : B_BAD_VALUE);
if (error == B_OK)
error = InitCheck();
ResourceItem *item = NULL;
if (error == B_OK) {
item = fContainer->ResourceAt(fContainer->IndexOf(type, id));
if (!item)
error = B_BAD_VALUE;
}
if (error == B_OK && fResourceFile)
error = fResourceFile->ReadResource(*item);
if (error == B_OK) {
if (item) {
ssize_t read = item->ReadAt(offset, data, length);
if (read < 0)
error = read;
} else
error = B_BAD_VALUE;
}
return error;
}
// FindResource
/*! \brief Finds a resource by type and ID and returns a copy of its data.
The caller is responsible for free()ing the returned memory.
\param type the type of the resource
\param id the ID of the resource
\param lengthFound a pointer to a variable into which the size of the
resource data shall be written
\return
- a pointer to the resource data, if everything went fine,
- \c NULL, if an error occured.
\deprecated Use LoadResource().
*/
void *
BResources::FindResource(type_code type, int32 id, size_t *lengthFound)
{
void *result = NULL;
size_t size = 0;
if (const void *data = LoadResource(type, id, &size)) {
if ((result = malloc(size)))
memcpy(result, data, size);
}
if (lengthFound)
*lengthFound = size;
return result;
}
// FindResource
/*! \brief Finds a resource by type and name and returns a copy of its data.
The caller is responsible for free()ing the returned memory.
\param type the type of the resource
\param name the name of the resource
\param lengthFound a pointer to a variable into which the size of the
resource data shall be written
\return
- a pointer to the resource data, if everything went fine,
- \c NULL, if an error occured.
\deprecated Use LoadResource().
*/
void *
BResources::FindResource(type_code type, const char *name, size_t *lengthFound)
{
void *result = NULL;
size_t size = 0;
if (const void *data = LoadResource(type, name, &size)) {
if ((result = malloc(size)))
memcpy(result, data, size);
}
if (lengthFound)
*lengthFound = size;
return result;
}
// FBC
void BResources::_ReservedResources1() {}
void BResources::_ReservedResources2() {}
void BResources::_ReservedResources3() {}
void BResources::_ReservedResources4() {}
void BResources::_ReservedResources5() {}
void BResources::_ReservedResources6() {}
void BResources::_ReservedResources7() {}
void BResources::_ReservedResources8() {}

View File

@ -1,220 +0,0 @@
/*
* Copyright 2002-2008, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Tyler Dauwalder, tyler@dauwalder.net
* Erik Jakowatz
* Ingo Weinhold, ingo_weinhold@gmx.de
*/
/*!
\file ResourcesContainer.cpp
ResourcesContainer implementation.
*/
#include "ResourcesContainer.h"
#include <stdio.h>
#include "ResourceItem.h"
namespace BPrivate {
namespace Storage {
ResourcesContainer::ResourcesContainer()
:
fResources(),
fIsModified(false)
{
}
ResourcesContainer::~ResourcesContainer()
{
MakeEmpty();
}
//! Returns false, if item is NULL or memory is insufficient, true otherwise.
bool
ResourcesContainer::AddResource(ResourceItem *item, int32 index, bool replace)
{
bool result = false;
if (item) {
// replace an item with the same type and id
if (replace)
delete RemoveResource(IndexOf(item->Type(), item->ID()));
int32 count = CountResources();
if (index < 0 || index > count)
index = count;
result = fResources.AddItem(item, count);
SetModified(true);
}
return result;
}
ResourceItem*
ResourcesContainer::RemoveResource(int32 index)
{
ResourceItem* item = (ResourceItem*)fResources.RemoveItem(index);
if (item)
SetModified(true);
return item;
}
bool
ResourcesContainer::RemoveResource(ResourceItem *item)
{
return RemoveResource(IndexOf(item));
}
void
ResourcesContainer::MakeEmpty()
{
for (int32 i = 0; ResourceItem *item = ResourceAt(i); i++)
delete item;
fResources.MakeEmpty();
SetModified(false);
}
void
ResourcesContainer::AssimilateResources(ResourcesContainer &container)
{
// Resistance is futile! ;-)
int32 newCount = container.CountResources();
for (int32 i = 0; i < newCount; i++) {
ResourceItem *item = container.ResourceAt(i);
if (item->IsLoaded())
AddResource(item);
else {
// That should not happen.
// Delete the item to have a consistent behavior.
delete item;
}
}
container.fResources.MakeEmpty();
container.SetModified(true);
SetModified(true);
}
int32
ResourcesContainer::IndexOf(ResourceItem *item) const
{
return fResources.IndexOf(item);
}
int32
ResourcesContainer::IndexOf(const void *data) const
{
int32 index = -1;
if (data) {
int32 count = CountResources();
for (int32 i = 0; index == -1 && i < count; i++) {
if (ResourceAt(i)->Data() == data)
index = i;
}
}
return index;
}
int32
ResourcesContainer::IndexOf(type_code type, int32 id) const
{
int32 index = -1;
int32 count = CountResources();
for (int32 i = 0; index == -1 && i < count; i++) {
ResourceItem *item = ResourceAt(i);
if (item->Type() == type && item->ID() == id)
index = i;
}
return index;
}
int32
ResourcesContainer::IndexOf(type_code type, const char *name) const
{
int32 index = -1;
int32 count = CountResources();
for (int32 i = 0; index == -1 && i < count; i++) {
ResourceItem *item = ResourceAt(i);
const char *itemName = item->Name();
if (item->Type() == type
&& ((name == NULL && itemName == NULL)
|| (name != NULL && itemName != NULL
&& !strcmp(name, itemName)))) {
index = i;
}
}
return index;
}
int32
ResourcesContainer::IndexOfType(type_code type, int32 typeIndex) const
{
int32 index = -1;
int32 count = CountResources();
for (int32 i = 0; index == -1 && i < count; i++) {
ResourceItem *item = ResourceAt(i);
if (item->Type() == type) {
if (typeIndex == 0)
index = i;
typeIndex--;
}
}
return index;
}
ResourceItem*
ResourcesContainer::ResourceAt(int32 index) const
{
return (ResourceItem*)fResources.ItemAt(index);
}
int32
ResourcesContainer::CountResources() const
{
return fResources.CountItems();
}
void
ResourcesContainer::SetModified(bool modified)
{
fIsModified = modified;
// If unmodified, set the resource item's modified flag as well.
if (!modified) {
int32 count = CountResources();
for (int32 i = 0; i < count; i++)
ResourceAt(i)->SetModified(false);
}
}
bool
ResourcesContainer::IsModified() const
{
bool isModified = fIsModified;
int32 count = CountResources();
for (int32 i = 0; !isModified && i < count; i++)
isModified |= ResourceAt(i)->IsModified();
return isModified;
}
} // namespace Storage
} // namespace BPrivate

View File

@ -1,218 +0,0 @@
//----------------------------------------------------------------------
// This software is part of the Haiku distribution and is covered
// by the MIT license.
//---------------------------------------------------------------------
/*!
\file SymLink.cpp
BSymLink implementation.
*/
#include <new>
#include <SymLink.h>
#include <Directory.h>
#include <Entry.h>
#include <Path.h>
#include <syscalls.h>
#include "storage_support.h"
using namespace std;
#ifdef USE_OPENBEOS_NAMESPACE
namespace OpenBeOS {
#endif
// constructor
//! Creates an uninitialized BSymLink object.
BSymLink::BSymLink()
: BNode()
{
}
// copy constructor
//! Creates a copy of the supplied BSymLink.
/*! \param link the BSymLink object to be copied
*/
BSymLink::BSymLink(const BSymLink &link)
: BNode(link)
{
}
// constructor
/*! \brief Creates a BSymLink and initializes it to the symbolic link referred
to by the supplied entry_ref.
\param ref the entry_ref referring to the symbolic link
*/
BSymLink::BSymLink(const entry_ref *ref)
: BNode(ref)
{
}
// constructor
/*! \brief Creates a BSymLink and initializes it to the symbolic link referred
to by the supplied BEntry.
\param entry the BEntry referring to the symbolic link
*/
BSymLink::BSymLink(const BEntry *entry)
: BNode(entry)
{
}
// constructor
/*! \brief Creates a BSymLink and initializes it to the symbolic link referred
to by the supplied path name.
\param path the symbolic link's path name
*/
BSymLink::BSymLink(const char *path)
: BNode(path)
{
}
// constructor
/*! \brief Creates a BSymLink and initializes it to the symbolic link referred
to by the supplied path name relative to the specified BDirectory.
\param dir the BDirectory, relative to which the symbolic link's path name
is given
\param path the symbolic link's path name relative to \a dir
*/
BSymLink::BSymLink(const BDirectory *dir, const char *path)
: BNode(dir, path)
{
}
// destructor
//! Frees all allocated resources.
/*! If the BSymLink is properly initialized, the symbolic link's file
descriptor is closed.
*/
BSymLink::~BSymLink()
{
}
// ReadLink
//! Reads the contents of the symbolic link into a buffer.
/*! \param buf the buffer
\param size the size of the buffer
\return
- the number of bytes written into the buffer
- \c B_BAD_VALUE: \c NULL \a buf or the object doesn't refer to a symbolic
link.
- \c B_FILE_ERROR: The object is not initialized.
- some other error code
*/
ssize_t
BSymLink::ReadLink(char *buffer, size_t size)
{
if (!buffer)
return B_BAD_VALUE;
if (InitCheck() != B_OK)
return B_FILE_ERROR;
status_t error = _kern_read_link(get_fd(), NULL, buffer, &size);
if (error < B_OK)
return error;
return size;
}
// MakeLinkedPath
/*! \brief Combines a directory path and the contents of this symbolic link to
an absolute path.
\param dirPath the path name of the directory
\param path the BPath object to be set to the resulting path name
\return
- \c the length of the resulting path name,
- \c B_BAD_VALUE: \c NULL \a dirPath or \a path or the object doesn't
refer to a symbolic link.
- \c B_FILE_ERROR: The object is not initialized.
- \c B_NAME_TOO_LONG: The resulting path name is too long.
- some other error code
*/
ssize_t
BSymLink::MakeLinkedPath(const char *dirPath, BPath *path)
{
// R5 seems to convert the dirPath to a BDirectory, which causes links to
// be resolved, i.e. a "/tmp" dirPath expands to "/boot/var/tmp".
// That does also mean, that the dirPath must exists!
if (!dirPath || !path)
return B_BAD_VALUE;
BDirectory dir(dirPath);
ssize_t result = dir.InitCheck();
if (result == B_OK)
result = MakeLinkedPath(&dir, path);
return result;
}
// MakeLinkedPath
/*! \brief Combines a directory path and the contents of this symbolic link to
an absolute path.
\param dir the BDirectory referring to the directory
\param path the BPath object to be set to the resulting path name
\return
- \c the length of the resulting path name,
- \c B_BAD_VALUE: \c NULL \a dir or \a path or the object doesn't
refer to a symbolic link.
- \c B_FILE_ERROR: The object is not initialized.
- \c B_NAME_TOO_LONG: The resulting path name is too long.
- some other error code
*/
ssize_t
BSymLink::MakeLinkedPath(const BDirectory *dir, BPath *path)
{
if (!dir || !path)
return B_BAD_VALUE;
char contents[B_PATH_NAME_LENGTH];
ssize_t result = ReadLink(contents, sizeof(contents));
if (result >= 0) {
if (BPrivate::Storage::is_absolute_path(contents))
result = path->SetTo(contents);
else
result = path->SetTo(dir, contents);
if (result == B_OK)
result = strlen(path->Path());
}
return result;
}
// IsAbsolute
//! Returns whether this BSymLink refers to an absolute link.
/*! /return
- \c true, if the object is properly initialized and the symbolic link it
refers to is an absolute link,
- \c false, otherwise.
*/
bool
BSymLink::IsAbsolute()
{
char contents[B_PATH_NAME_LENGTH];
bool result = (ReadLink(contents, sizeof(contents)) >= 0);
if (result)
result = BPrivate::Storage::is_absolute_path(contents);
return result;
}
void BSymLink::_MissingSymLink1() {}
void BSymLink::_MissingSymLink2() {}
void BSymLink::_MissingSymLink3() {}
void BSymLink::_MissingSymLink4() {}
void BSymLink::_MissingSymLink5() {}
void BSymLink::_MissingSymLink6() {}
//! Returns the BSymLink's file descriptor.
/*! To be used instead of accessing the BNode's private \c fFd member directly.
\return the file descriptor, or -1, if not properly initialized.
*/
int
BSymLink::get_fd() const
{
return fFd;
}
#ifdef USE_OPENBEOS_NAMESPACE
}; // namespace OpenBeOS
#endif

View File

@ -1,510 +0,0 @@
/*
* Copyright 2002-2006, Haiku Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* Tyler Dauwalder
* Ingo Weinhold, bonefish@users.sf.net
*/
/*!
\file storage_support.cpp
Implementations of miscellaneous internal Storage Kit support functions.
*/
#include <new>
#include <ctype.h>
#include <string.h>
#include <StorageDefs.h>
#include <SupportDefs.h>
#include <syscalls.h>
#include "storage_support.h"
namespace BPrivate {
namespace Storage {
/*! \param path the path
\return \c true, if \a path is not \c NULL and absolute, \c false otherwise
*/
bool
is_absolute_path(const char *path)
{
return (path && path[0] == '/');
}
// parse_path
/*! \brief Parses the supplied path and returns the position of the leaf name
part of the path and the length of its directory path part.
The value returned in \a fullPath is guaranteed to be > 0, i.e. the
function always returns a non-empty directory path part. The leaf name
part may be empty though (i.e. \code leafStart == leafEnd \endcode), which
will happen, if the supplied path consists only of one component.
\param fullPath The path to be parsed.
\param dirEnd Reference to a variable into which the end index of the
directory part shall be written. The index is exclusive.
\param leafStart Reference to a variable into which the start index of
the leaf name part shall be written. The index is inclusive.
\param leafEnd Reference to a variable into which the end index of
the leaf name part shall be written. The index is exclusive.
\return \c B_OK, if everything went fine, B_BAD_VALUE, if the supplied
path is invalid.
*/
status_t
parse_path(const char *fullPath, int &dirEnd, int &leafStart, int &leafEnd)
{
// check path and get length
if (!fullPath)
return B_BAD_VALUE;
int pathLen = strlen(fullPath);
if (pathLen == 0)
return B_BAD_VALUE;
// find then end of the leaf name (skip trailing '/')
int i = pathLen - 1;
while (i >= 0 && fullPath[i] == '/')
i--;
leafEnd = i + 1;
if (leafEnd == 0) {
// fullPath consists of slashes only
dirEnd = leafStart = leafEnd = 1;
return B_OK;
}
// find the start of the leaf name
while (i >= 0 && fullPath[i] != '/')
i--;
leafStart = i + 1;
if (leafStart == 0) {
// fullPath contains only one component
dirEnd = leafStart = leafEnd;
return B_OK;
}
// find the end of the dir path
while (i >= 0 && fullPath[i] == '/')
i--;
dirEnd = i + 1;
if (dirEnd == 0) // => fullPath[0] == '/' (an absolute path)
dirEnd = 1;
return B_OK;
}
// parse_path
/*! \brief Parses the supplied path and returns the leaf name part of the path
and its directory path part.
The value returned in \a fullPath is guaranteed to be > 0, i.e. the
function always returns a non-empty directory path part. The leaf name
part may be empty though (i.e. \code leafStart == leafEnd \endcode), which
will happen, if the supplied path consists only of one component.
\param fullPath The path to be parsed.
\param dirPath Pointer to a character array of size \c B_PATH_NAME_LENGTH
or greater, into which the directory part shall be written.
May be \c NULL.
\param leaf Pointer to a character array of size \c B_FILE_NAME_LENGTH
or greater, into which the leaf name part shall be written.
May be \c NULL.
\return \c B_OK, if everything went fine, B_BAD_VALUE, if the supplied
path is invalid.
*/
status_t
parse_path(const char *fullPath, char *dirPath, char *leaf)
{
// parse the path and check the lengths
int leafStart, leafEnd, dirEnd;
status_t error = parse_path(fullPath, dirEnd, leafStart, leafEnd);
if (error != B_OK)
return error;
if (dirEnd >= B_PATH_NAME_LENGTH
|| leafEnd - leafStart >= B_FILE_NAME_LENGTH) {
return B_NAME_TOO_LONG;
}
// copy the result strings
if (dirPath)
strlcpy(dirPath, fullPath, dirEnd + 1);
if (leaf)
strlcpy(leaf, fullPath + leafStart, leafEnd - leafStart + 1);
return B_OK;
}
// internal_parse_path
static
void
internal_parse_path(const char *fullPath, int &leafStart, int &leafEnd,
int &pathEnd)
{
if (fullPath == NULL)
return;
enum PathParserState { PPS_START, PPS_LEAF } state = PPS_START;
int len = strlen(fullPath);
leafStart = -1;
leafEnd = -1;
pathEnd = -2;
bool loop = true;
for (int pos = len-1; ; pos--) {
if (pos < 0)
break;
switch (state) {
case PPS_START:
// Skip all trailing '/' chars, then move on to
// reading the leaf name
if (fullPath[pos] != '/') {
leafEnd = pos;
state = PPS_LEAF;
}
break;
case PPS_LEAF:
// Read leaf name chars until we hit a '/' char
if (fullPath[pos] == '/') {
leafStart = pos+1;
pathEnd = pos-1;
loop = false;
}
break;
}
if (!loop)
break;
}
}
/*! The caller is responsible for deleting the returned directory path name
and the leaf name.
\param fullPath the path name to be split
\param path a variable the directory path name pointer shall
be written into, may be NULL
\param leaf a variable the leaf name pointer shall be
written into, may be NULL
*/
status_t
split_path(const char *fullPath, char *&path, char *&leaf)
{
return split_path(fullPath, &path, &leaf);
}
/*! The caller is responsible for deleting the returned directory path name
and the leaf name.
\param fullPath the path name to be split
\param path a pointer to a variable the directory path name pointer shall
be written into, may be NULL
\param leaf a pointer to a variable the leaf name pointer shall be
written into, may be NULL
*/
status_t
split_path(const char *fullPath, char **path, char **leaf)
{
if (path)
*path = NULL;
if (leaf)
*leaf = NULL;
if (fullPath == NULL)
return B_BAD_VALUE;
int leafStart, leafEnd, pathEnd, len;
internal_parse_path(fullPath, leafStart, leafEnd, pathEnd);
try {
// Tidy up/handle special cases
if (leafEnd == -1) {
// Handle special cases
if (fullPath[0] == '/') {
// Handle "/"
if (path) {
*path = new char[2];
(*path)[0] = '/';
(*path)[1] = 0;
}
if (leaf) {
*leaf = new char[2];
(*leaf)[0] = '.';
(*leaf)[1] = 0;
}
return B_OK;
} else if (fullPath[0] == 0) {
// Handle "", which we'll treat as "./"
if (path) {
*path = new char[1];
(*path)[0] = 0;
}
if (leaf) {
*leaf = new char[2];
(*leaf)[0] = '.';
(*leaf)[1] = 0;
}
return B_OK;
}
} else if (leafStart == -1) {
// fullPath is just an entry name, no parent directories specified
leafStart = 0;
} else if (pathEnd == -1) {
// The path is '/' (since pathEnd would be -2 if we had
// run out of characters before hitting a '/')
pathEnd = 0;
}
// Alloc new strings and copy the path and leaf over
if (path) {
if (pathEnd == -2) {
// empty path
*path = new char[2];
(*path)[0] = '.';
(*path)[1] = 0;
} else {
// non-empty path
len = pathEnd + 1;
*path = new char[len+1];
memcpy(*path, fullPath, len);
(*path)[len] = 0;
}
}
if (leaf) {
len = leafEnd - leafStart + 1;
*leaf = new char[len+1];
memcpy(*leaf, fullPath + leafStart, len);
(*leaf)[len] = 0;
}
} catch (std::bad_alloc exception) {
if (path)
delete[] *path;
if (leaf)
delete[] *leaf;
return B_NO_MEMORY;
}
return B_OK;
}
/*! The length of the first component is returned as well as the index at
which the next one starts. These values are only valid, if the function
returns \c B_OK.
\param path the path to be parsed
\param length the variable the length of the first component is written
into
\param nextComponent the variable the index of the next component is
written into. \c 0 is returned, if there is no next component.
\return \c B_OK, if \a path is not \c NULL, \c B_BAD_VALUE otherwise
*/
status_t
parse_first_path_component(const char *path, int32& length,
int32& nextComponent)
{
status_t error = (path ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
int32 i = 0;
// find first '/' or end of name
for (; path[i] != '/' && path[i] != '\0'; i++);
// handle special case "/..." (absolute path)
if (i == 0 && path[i] != '\0')
i = 1;
length = i;
// find last '/' or end of name
for (; path[i] == '/' && path[i] != '\0'; i++);
if (path[i] == '\0') // this covers "" as well
nextComponent = 0;
else
nextComponent = i;
}
return error;
}
/*! A string containing the first component is returned and the index, at
which the next one starts. These values are only valid, if the function
returns \c B_OK.
\param path the path to be parsed
\param component the variable the pointer to the newly allocated string
containing the first path component is written into. The caller
is responsible for delete[]'ing the string.
\param nextComponent the variable the index of the next component is
written into. \c 0 is returned, if there is no next component.
\return \c B_OK, if \a path is not \c NULL, \c B_BAD_VALUE otherwise
*/
status_t
parse_first_path_component(const char *path, char *&component,
int32& nextComponent)
{
int32 length;
status_t error = parse_first_path_component(path, length, nextComponent);
if (error == B_OK) {
component = new(std::nothrow) char[length + 1];
if (component) {
strncpy(component, path, length);
component[length] = '\0';
} else
error = B_NO_MEMORY;
}
return error;
}
/*! An entry name is considered valid, if its length doesn't exceed
\c B_FILE_NAME_LENGTH (including the terminating null) and it doesn't
contain any \c "/".
\param entry the entry name
\return
- \c B_OK, if \a entry is valid,
- \c B_BAD_VALUE, if \a entry is \c NULL or contains a "/",
- \c B_NAME_TOO_LONG, if \a entry is too long
\note \c "" is considered a valid entry name.
*/
status_t
check_entry_name(const char *entry)
{
status_t error = (entry ? B_OK : B_BAD_VALUE);
if (error == B_OK) {
if (strlen(entry) >= B_FILE_NAME_LENGTH)
error = B_NAME_TOO_LONG;
}
if (error == B_OK) {
for (int32 i = 0; error == B_OK && entry[i] != '\0'; i++) {
if (entry[i] == '/')
error = B_BAD_VALUE;
}
}
return error;
}
/*! An path name is considered valid, if its length doesn't exceed
\c B_PATH_NAME_LENGTH (including the terminating null) and each of
its components is a valid entry name.
\param entry the entry name
\return
- \c B_OK, if \a path is valid,
- \c B_BAD_VALUE, if \a path is \c NULL,
- \c B_NAME_TOO_LONG, if \a path, or any of its components is too long
\note \c "" is considered a valid path name.
*/
status_t
check_path_name(const char *path)
{
status_t error = (path ? B_OK : B_BAD_VALUE);
// check the path components
const char *remainder = path;
int32 length, nextComponent;
do {
error = parse_first_path_component(remainder, length, nextComponent);
if (error == B_OK) {
if (length >= B_FILE_NAME_LENGTH)
error = B_NAME_TOO_LONG;
remainder += nextComponent;
}
} while (error == B_OK && nextComponent != 0);
// check the length of the path
if (error == B_OK && strlen(path) >= B_PATH_NAME_LENGTH)
error = B_NAME_TOO_LONG;
return error;
}
std::string
to_lower(const char *str)
{
std::string result;
to_lower(str, result);
return result;
}
void
to_lower(const char *str, std::string &result)
{
if (str) {
result = "";
for (int i = 0; i < (int)strlen(str); i++)
result += tolower(str[i]);
} else
result = "(null)";
}
void
to_lower(const char *str, char *result)
{
if (str && result) {
int i;
for (i = 0; i < (int)strlen(str); i++)
result[i] = tolower(str[i]);
result[i] = 0;
}
}
void
to_lower(char *str)
{
to_lower(str, str);
}
void escape_path(const char *str, char *result)
{
if (str && result) {
int32 len = strlen(str);
for (int32 i = 0; i < len; i++) {
char ch = str[i];
char escapeChar = 0;
switch (ch) {
case ' ':
case '\'':
case '"':
case '?':
case '\\':
case '(':
case ')':
case '[':
case ']':
case '*':
case '^':
escapeChar = ch;
break;
}
if (escapeChar) {
*(result++) = '\\';
*(result++) = escapeChar;
} else {
*(result++) = ch;
}
}
*result = 0;
}
}
void escape_path(char *str)
{
if (str) {
char *copy = new(std::nothrow) char[strlen(str)+1];
if (copy) {
strcpy(copy, str);
escape_path(copy, str);
}
delete [] copy;
}
}
// device_is_root_device
bool
device_is_root_device(dev_t device)
{
return device == 1;
}
// Close
void
FDCloser::Close()
{
if (fFD >= 0)
_kern_close(fFD);
fFD = -1;
}
}; // namespace Storage
}; // namespace BPrivate

View File

@ -1,33 +0,0 @@
/*
** Copyright 2004, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
** Distributed under the terms of the Haiku License.
*/
#include <Beep.h>
#include <stdio.h>
status_t
system_beep(const char *eventName)
{
printf("beep event \"%s\" requested.\n", eventName);
// ToDo: ask media server to beep around
return B_ERROR;
}
status_t
beep()
{
return system_beep(NULL);
}
status_t
add_system_beep_event(const char *eventName, uint32 flags _BEEP_FLAGS)
{
// ToDo: ask media server to add beep event
return B_ERROR;
}

View File

@ -1,150 +0,0 @@
/*
* Copyright (c) 2003 Marcus Overhagen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <BlockCache.h>
#include <Debug.h>
#include <string.h>
#include <stdlib.h>
#include <new>
#define MAGIC1 0x9183f4d9
#define MAGIC2 0xa6b3c87d
struct BBlockCache::_FreeBlock {
DEBUG_ONLY( uint32 magic1; )
_FreeBlock *next;
DEBUG_ONLY( uint32 magic2; )
};
// The requirements set by the BeBook's description of the destructor,
// as well as Get() function, allowing the caller to dispose of the
// memory, do not allow to allocate one large block to be used as pool.
// Thus we need to create multiple small ones.
// We maintain a list of free blocks.
BBlockCache::BBlockCache(uint32 blockCount,
size_t blockSize,
uint32 allocationType)
: fFreeList(0),
fBlockSize(blockSize),
fFreeBlocks(0),
fBlockCount(blockCount),
fLocker("some BBlockCache lock"),
fAlloc(0),
fFree(0)
{
switch (allocationType) {
case B_OBJECT_CACHE:
fAlloc = &operator new[];
fFree = &operator delete[];
break;
case B_MALLOC_CACHE:
default:
fAlloc = &malloc;
fFree = &free;
break;
}
// To properly maintain a list of free buffers, a buffer must be
// large enough to contain the _FreeBlock struct that is used.
if (blockSize < sizeof(_FreeBlock))
blockSize = sizeof(_FreeBlock);
// should have at least one block
if (blockCount == 0)
blockCount = 1;
// create blocks and put them into the free list
while (blockCount--) {
_FreeBlock *block = reinterpret_cast<_FreeBlock *>(fAlloc(blockSize));
if (!block)
break;
fFreeBlocks++;
block->next = fFreeList;
fFreeList = block;
DEBUG_ONLY(block->magic1 = MAGIC1);
DEBUG_ONLY(block->magic2 = MAGIC2 + (uint32)block->next);
}
}
BBlockCache::~BBlockCache()
{
// walk the free list and deallocate all blocks
fLocker.Lock();
while (fFreeList) {
ASSERT(fFreeList->magic1 == MAGIC1);
ASSERT(fFreeList->magic2 == MAGIC2 + (uint32)fFreeList->next);
void *pointer = fFreeList;
fFreeList = fFreeList->next;
DEBUG_ONLY(memset(pointer, 0xCC, sizeof(_FreeBlock)));
fFree(pointer);
}
fLocker.Unlock();
}
void *
BBlockCache::Get(size_t blockSize)
{
if (!fLocker.Lock())
return 0;
void *pointer;
if (blockSize == fBlockSize && fFreeList != 0) {
// we can take a block from the list
ASSERT(fFreeList->magic1 == MAGIC1);
ASSERT(fFreeList->magic2 == MAGIC2 + (uint32)fFreeList->next);
pointer = fFreeList;
fFreeList = fFreeList->next;
fFreeBlocks--;
DEBUG_ONLY(memset(pointer, 0xCC, sizeof(_FreeBlock)));
} else {
if (blockSize < sizeof(_FreeBlock))
blockSize = sizeof(_FreeBlock);
pointer = fAlloc(blockSize);
DEBUG_ONLY(if (pointer) memset(pointer, 0xCC, sizeof(_FreeBlock)));
}
fLocker.Unlock();
return pointer;
}
void
BBlockCache::Save(void *pointer, size_t blockSize)
{
if (!fLocker.Lock())
return;
if (blockSize == fBlockSize && fFreeBlocks < fBlockCount) {
// the block needs to be returned to the cache
_FreeBlock *block = reinterpret_cast<_FreeBlock *>(pointer);
block->next = fFreeList;
fFreeList = block;
fFreeBlocks++;
DEBUG_ONLY(block->magic1 = MAGIC1);
DEBUG_ONLY(block->magic2 = MAGIC2 + (uint32)block->next);
} else {
DEBUG_ONLY(memset(pointer, 0xCC, sizeof(_FreeBlock)));
fFree(pointer);
}
fLocker.Unlock();
}
void BBlockCache::_ReservedBlockCache1() {}
void BBlockCache::_ReservedBlockCache2() {}

View File

@ -1,176 +0,0 @@
/*
** Copyright 2004, Axel Dörfler, axeld@pinc-software.de. All rights reserved.
** Distributed under the terms of the Haiku License.
*/
#include <ByteOrder.h>
#include <Messenger.h>
#include <MessengerPrivate.h>
status_t
swap_data(type_code type, void *_data, size_t length, swap_action action)
{
if (_data == NULL || length == 0)
return B_BAD_VALUE;
switch (type) {
// allowed types
case B_INT16_TYPE:
case B_UINT16_TYPE:
case B_FLOAT_TYPE:
case B_INT32_TYPE:
case B_UINT32_TYPE:
case B_SIZE_T_TYPE:
case B_SSIZE_T_TYPE:
case B_TIME_TYPE:
case B_POINTER_TYPE:
case B_RECT_TYPE:
case B_POINT_TYPE:
case B_DOUBLE_TYPE:
case B_INT64_TYPE:
case B_UINT64_TYPE:
case B_OFF_T_TYPE:
case B_MESSENGER_TYPE:
break;
default:
// not swappable or recognized type!
return B_BAD_VALUE;
}
// is there anything to do?
#if B_HOST_IS_LENDIAN
if (action == B_SWAP_HOST_TO_LENDIAN || action == B_SWAP_LENDIAN_TO_HOST)
return B_OK;
#else
if (action == B_SWAP_HOST_TO_BENDIAN || action == B_SWAP_BENDIAN_TO_HOST)
return B_OK;
#endif
switch (type) {
// 16 bit types
case B_INT16_TYPE:
case B_UINT16_TYPE:
{
uint16 *data = (uint16 *)_data;
uint16 *end = (uint16 *)((addr_t)_data + length);
while (data < end) {
*data = __swap_int16(*data);
data++;
}
break;
}
// 32 bit types
case B_FLOAT_TYPE:
case B_INT32_TYPE:
case B_UINT32_TYPE:
case B_SIZE_T_TYPE:
case B_SSIZE_T_TYPE:
case B_TIME_TYPE:
case B_POINTER_TYPE:
case B_RECT_TYPE:
case B_POINT_TYPE:
{
// ToDo: some of these types may not be 32-bit on 64-bit platforms!
uint32 *data = (uint32 *)_data;
uint32 *end = (uint32 *)((addr_t)_data + length);
while (data < end) {
*data = __swap_int32(*data);
data++;
}
break;
}
// 64 bit types
case B_DOUBLE_TYPE:
case B_INT64_TYPE:
case B_UINT64_TYPE:
case B_OFF_T_TYPE:
{
uint64 *data = (uint64 *)_data;
uint64 *end = (uint64 *)((addr_t)_data + length);
while (data < end) {
*data = __swap_int64(*data);
data++;
}
break;
}
// special types
case B_MESSENGER_TYPE:
{
BMessenger *messenger = (BMessenger *)_data;
BMessenger *end = (BMessenger *)((addr_t)_data + length);
while (messenger < end) {
BMessenger::Private messengerPrivate(messenger);
// ToDo: if the additional fields change, this function has to be updated!
messengerPrivate.SetTo(
__swap_int32(messengerPrivate.Team()),
__swap_int32(messengerPrivate.Port()),
__swap_int32(messengerPrivate.Token()));
messenger++;
}
break;
}
}
return B_OK;
}
bool
is_type_swapped(type_code type)
{
// Returns true when the type is in the host's native format
// Looks like a pretty strange function to me :)
switch (type) {
case B_ANY_TYPE:
case B_BOOL_TYPE:
case B_CHAR_TYPE:
case B_COLOR_8_BIT_TYPE:
case B_DOUBLE_TYPE:
case B_FLOAT_TYPE:
case B_GRAYSCALE_8_BIT_TYPE:
case B_INT64_TYPE:
case B_INT32_TYPE:
case B_INT16_TYPE:
case B_INT8_TYPE:
case B_MESSAGE_TYPE:
case B_MESSENGER_TYPE:
case B_MIME_TYPE:
case B_MONOCHROME_1_BIT_TYPE:
case B_OBJECT_TYPE:
case B_OFF_T_TYPE:
case B_PATTERN_TYPE:
case B_POINTER_TYPE:
case B_POINT_TYPE:
case B_RAW_TYPE:
case B_RECT_TYPE:
case B_REF_TYPE:
case B_RGB_32_BIT_TYPE:
case B_RGB_COLOR_TYPE:
case B_SIZE_T_TYPE:
case B_SSIZE_T_TYPE:
case B_STRING_TYPE:
case B_TIME_TYPE:
case B_UINT64_TYPE:
case B_UINT32_TYPE:
case B_UINT16_TYPE:
case B_UINT8_TYPE:
case B_MEDIA_PARAMETER_TYPE:
case B_MEDIA_PARAMETER_WEB_TYPE:
case B_MEDIA_PARAMETER_GROUP_TYPE:
return true;
}
return false;
}

View File

@ -1,172 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2002, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: DataBuffer.cpp
// Author(s): Erik Jaesler <erik@cgsoftware.com>
//
// Description: Provides the backing store for BMessages
//
//
//------------------------------------------------------------------------------
// Standard Includes -----------------------------------------------------------
#include <string.h>
// System Includes -------------------------------------------------------------
// Project Includes ------------------------------------------------------------
#include <DataBuffer.h>
// Local Includes --------------------------------------------------------------
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
namespace BPrivate {
//------------------------------------------------------------------------------
BDataBuffer::BDataBuffer(size_t len)
{
BDataReference::Create(len, fDataRef);
}
//------------------------------------------------------------------------------
BDataBuffer::BDataBuffer(const void* data, size_t len, bool copy)
{
BDataReference::Create(data, len, fDataRef, copy);
}
//------------------------------------------------------------------------------
BDataBuffer::BDataBuffer(const BDataBuffer& rhs, bool copy)
{
if (this != &rhs)
{
if (copy)
{
BDataReference::Create(rhs.Buffer(), rhs.BufferSize(),
fDataRef, copy);
}
else
{
rhs.fDataRef->Acquire(fDataRef);
}
}
}
//------------------------------------------------------------------------------
BDataBuffer::~BDataBuffer()
{
if (fDataRef)
{
fDataRef->Release(fDataRef);
}
}
//------------------------------------------------------------------------------
BDataBuffer& BDataBuffer::operator=(const BDataBuffer& rhs)
{
if (this != &rhs)
{
rhs.fDataRef->Acquire(fDataRef);
}
return *this;
}
//------------------------------------------------------------------------------
size_t BDataBuffer::BufferSize() const
{
return fDataRef->Size();
}
//------------------------------------------------------------------------------
const void* BDataBuffer::Buffer() const
{
return (const void*)fDataRef->Data();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void BDataBuffer::BDataReference::Create(const void* data, size_t len,
BDataReference*& ref, bool copy)
{
BDataReference* temp = new BDataReference(data, len, copy);
temp->Acquire(ref);
}
//------------------------------------------------------------------------------
void BDataBuffer::BDataReference::Create(size_t len, BDataReference*& ref)
{
BDataReference* temp = new BDataReference(len);
temp->Acquire(ref);
}
//------------------------------------------------------------------------------
void BDataBuffer::BDataReference::Acquire(BDataReference*& ref)
{
ref = this;
++fCount;
}
//------------------------------------------------------------------------------
void BDataBuffer::BDataReference::Release(BDataReference*& ref)
{
ref = NULL;
--fCount;
if (fCount <= 0)
{
delete this;
}
}
//------------------------------------------------------------------------------
BDataBuffer::BDataReference::BDataReference(const void* data, size_t len,
bool copy)
: fData(NULL), fSize(len), fCount(0)
{
if (copy)
{
fData = new char[fSize];
memcpy((void*)fData, data, fSize);
}
else
{
fData = (char*)data;
}
}
//------------------------------------------------------------------------------
BDataBuffer::BDataReference::BDataReference(size_t len)
: fData(NULL), fSize(len), fCount(0)
{
fData = new char[fSize];
}
//------------------------------------------------------------------------------
BDataBuffer::BDataReference::~BDataReference()
{
if (fData)
{
delete[] fData;
fData = NULL;
}
}
//------------------------------------------------------------------------------
} // namespace BPrivate
/*
* $Log $
*
* $Id $
*
*/

View File

@ -1,461 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2005, Haiku, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: DataIO.cpp
// Author(s): Stefano Ceccherini (burton666@libero.it)
// The Storage Team
// Description: Pure virtual BDataIO and BPositioIO classes provide
// the protocol for Read()/Write()/Seek().
//
// BMallocIO and BMemoryIO classes implement the protocol,
// as does BFile in the Storage Kit.
//------------------------------------------------------------------------------
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <DataIO.h>
// *** BDataIO ***
// Construction
BDataIO::BDataIO()
{
}
// Destruction
BDataIO::~BDataIO()
{
}
// Private or Reserved
BDataIO::BDataIO(const BDataIO &)
{
//Copying not allowed
}
BDataIO &
BDataIO::operator=(const BDataIO &)
{
//Copying not allowed
return *this;
}
// FBC
void BDataIO::_ReservedDataIO1(){}
void BDataIO::_ReservedDataIO2(){}
void BDataIO::_ReservedDataIO3(){}
void BDataIO::_ReservedDataIO4(){}
#if !_PR3_COMPATIBLE_
void BDataIO::_ReservedDataIO5(){}
void BDataIO::_ReservedDataIO6(){}
void BDataIO::_ReservedDataIO7(){}
void BDataIO::_ReservedDataIO8(){}
void BDataIO::_ReservedDataIO9(){}
void BDataIO::_ReservedDataIO10(){}
void BDataIO::_ReservedDataIO11(){}
void BDataIO::_ReservedDataIO12(){}
#endif
// *** BPositionIO ***
// Construction
BPositionIO::BPositionIO()
{
}
// Destruction
BPositionIO::~BPositionIO()
{
}
// Read
ssize_t
BPositionIO::Read(void *buffer, size_t size)
{
off_t curPos = Position();
ssize_t result = ReadAt(curPos, buffer, size);
if (result > 0)
Seek(result, SEEK_CUR);
return result;
}
// Write
ssize_t
BPositionIO::Write(const void *buffer, size_t size)
{
off_t curPos = Position();
ssize_t result = WriteAt(curPos, buffer, size);
if (result > 0)
Seek(result, SEEK_CUR);
return result;
}
// SetSize
status_t
BPositionIO::SetSize(off_t size)
{
return B_ERROR;
}
// FBC
void BPositionIO::_ReservedPositionIO1(){}
void BPositionIO::_ReservedPositionIO2(){}
void BPositionIO::_ReservedPositionIO3(){}
void BPositionIO::_ReservedPositionIO4(){}
#if !_PR3_COMPATIBLE_
void BPositionIO::_ReservedPositionIO5(){}
void BPositionIO::_ReservedPositionIO6(){}
void BPositionIO::_ReservedPositionIO7(){}
void BPositionIO::_ReservedPositionIO8(){}
void BPositionIO::_ReservedPositionIO9(){}
void BPositionIO::_ReservedPositionIO10(){}
void BPositionIO::_ReservedPositionIO11(){}
void BPositionIO::_ReservedPositionIO12(){}
#endif
// *** BMemoryIO ***
// Construction
BMemoryIO::BMemoryIO(void *p, size_t len)
:fReadOnly(false),
fBuf(static_cast<char*>(p)),
fLen(len),
fPhys(len),
fPos(0)
{
}
BMemoryIO::BMemoryIO(const void *p, size_t len)
:fReadOnly(true),
fBuf(const_cast<char*>(static_cast<const char*>(p))),
fLen(len),
fPhys(len),
fPos(0)
{
}
// Destruction
BMemoryIO::~BMemoryIO()
{
}
// ReadAt
ssize_t
BMemoryIO::ReadAt(off_t pos, void *buffer, size_t size)
{
if (buffer == NULL || pos < 0)
return B_BAD_VALUE;
ssize_t sizeRead = 0;
if (pos < (off_t)fLen) {
sizeRead = min_c((off_t)size, (off_t)fLen - pos);
memcpy(buffer, fBuf + pos, sizeRead);
}
return sizeRead;
}
// WriteAt
ssize_t
BMemoryIO::WriteAt(off_t pos, const void *buffer, size_t size)
{
if (fReadOnly)
return B_NOT_ALLOWED;
if (buffer == NULL || pos < 0)
return B_BAD_VALUE;
ssize_t sizeWritten = 0;
if (pos < (off_t)fPhys) {
sizeWritten = min_c((off_t)size, (off_t)fPhys - pos);
memcpy(fBuf + pos, buffer, sizeWritten);
}
if (pos + sizeWritten > (off_t)fLen)
fLen = pos + sizeWritten;
return sizeWritten;
}
// Seek
off_t
BMemoryIO::Seek(off_t position, uint32 seek_mode)
{
switch (seek_mode) {
case SEEK_SET:
fPos = position;
break;
case SEEK_CUR:
fPos += position;
break;
case SEEK_END:
fPos = fLen + position;
break;
default:
break;
}
return fPos;
}
// Position
off_t
BMemoryIO::Position() const
{
return fPos;
}
// SetSize
status_t
BMemoryIO::SetSize(off_t size)
{
status_t err = B_ERROR;
if (fReadOnly)
return B_NOT_ALLOWED;
if (size <= (off_t)fPhys) {
err = B_OK;
fLen = size;
}
return err;
}
// Private or Reserved
BMemoryIO::BMemoryIO(const BMemoryIO &)
{
//Copying not allowed
}
BMemoryIO &
BMemoryIO::operator=(const BMemoryIO &)
{
//Copying not allowed
return *this;
}
// FBC
void BMemoryIO::_ReservedMemoryIO1(){}
void BMemoryIO::_ReservedMemoryIO2(){}
// *** BMallocIO ***
// Construction
BMallocIO::BMallocIO()
: fBlockSize(256),
fMallocSize(0),
fLength(0),
fData(NULL),
fPosition(0)
{
}
// Destruction
BMallocIO::~BMallocIO()
{
free(fData);
}
// ReadAt
ssize_t
BMallocIO::ReadAt(off_t pos, void *buffer, size_t size)
{
if (buffer == NULL)
return B_BAD_VALUE;
ssize_t sizeRead = 0;
if (pos < (off_t)fLength) {
sizeRead = min_c((off_t)size, (off_t)fLength - pos);
memcpy(buffer, fData + pos, sizeRead);
}
return sizeRead;
}
// WriteAt
ssize_t
BMallocIO::WriteAt(off_t pos, const void *buffer, size_t size)
{
if (buffer == NULL)
return B_BAD_VALUE;
size_t newSize = max_c(pos + (off_t)size, (off_t)fLength);
status_t error = B_OK;
if (newSize > fMallocSize)
error = SetSize(newSize);
if (error == B_OK) {
memcpy(fData + pos, buffer, size);
if (pos + size > fLength)
fLength = pos + size;
}
return error != B_OK ? error : size;
}
// Seek
off_t
BMallocIO::Seek(off_t position, uint32 seekMode)
{
switch (seekMode) {
case SEEK_SET:
fPosition = position;
break;
case SEEK_END:
fPosition = fLength + position;
break;
case SEEK_CUR:
fPosition += position;
break;
default:
break;
}
return fPosition;
}
// Position
off_t
BMallocIO::Position() const
{
return fPosition;
}
// SetSize
status_t
BMallocIO::SetSize(off_t size)
{
status_t error = B_OK;
if (size == 0) {
// size == 0, free the memory
free(fData);
fData = NULL;
fMallocSize = 0;
} else {
// size != 0, see, if necessary to resize
size_t newSize = (size + fBlockSize - 1) / fBlockSize * fBlockSize;
if (size != (off_t)fMallocSize) {
// we need to resize
if (char *newData = static_cast<char*>(realloc(fData, newSize))) {
// set the new area to 0
if (newSize > fMallocSize)
memset(newData + fMallocSize, 0, newSize - fMallocSize);
fData = newData;
fMallocSize = newSize;
} else // couldn't alloc the memory
error = B_NO_MEMORY;
}
}
if (error == B_OK)
fLength = size;
return error;
}
// SetBlockSize
void
BMallocIO::SetBlockSize(size_t blockSize)
{
if (blockSize == 0)
blockSize = 1;
if (blockSize != fBlockSize)
fBlockSize = blockSize;
}
// Buffer
const void *
BMallocIO::Buffer() const
{
return fData;
}
// BufferLength
size_t
BMallocIO::BufferLength() const
{
return fLength;
}
// Private or Reserved
BMallocIO::BMallocIO(const BMallocIO &)
{
// copying not allowed...
}
BMallocIO &
BMallocIO::operator=(const BMallocIO &)
{
// copying not allowed...
return *this;
}
// FBC
void BMallocIO::_ReservedMallocIO1() {}
void BMallocIO::_ReservedMallocIO2() {}
/*
* $Log $
*
* $Id $
*
*/

View File

@ -1,46 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2005, Haiku, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: Flattenable.cpp
// Author: unknown
// Description: Provides functionality for subclasses to convert to
// a run of bytes
//------------------------------------------------------------------------------
#include <stdio.h>
#include <Flattenable.h>
// AllowsTypeCode
bool
BFlattenable::AllowsTypeCode(type_code code) const
{
return (TypeCode() == code);
}
// destructor
BFlattenable::~BFlattenable()
{
}
void BFlattenable::_ReservedFlattenable1() {}
void BFlattenable::_ReservedFlattenable2() {}
void BFlattenable::_ReservedFlattenable3() {}

View File

@ -4,6 +4,8 @@ UsePrivateBuildHeaders app interface shared ;
USES_BE_API on <libbe_build>support_kit.o = true ;
SEARCH_SOURCE += [ FDirName $(HAIKU_TOP) src kits support ] ;
BuildPlatformMergeObjectPIC <libbe_build>support_kit.o :
Archivable.cpp
BlockCache.cpp

View File

@ -1,464 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2008, Haiku, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: List.cpp
// Author(s): The Storage kit Team
// Isaac Yonemoto
// Rene Gollent
// Description: BList class provides storage for pointers.
// Not thread safe.
//------------------------------------------------------------------------------
// Standard Includes -----------------------------------------------------------
#include <List.h>
// System Includes -------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// helper function
static inline
void
move_items(void** items, int32 offset, int32 count)
{
if (count > 0 && offset != 0)
memmove(items + offset, items, count * sizeof(void*));
}
// constructor
BList::BList(int32 count)
: fObjectList(NULL),
fPhysicalSize(0),
fItemCount(0),
fBlockSize(count),
fResizeThreshold(0)
{
if (fBlockSize <= 0)
fBlockSize = 1;
_ResizeArray(fItemCount);
}
// copy constructor
BList::BList(const BList& anotherList)
: fObjectList(NULL),
fPhysicalSize(0),
fItemCount(0),
fBlockSize(anotherList.fBlockSize)
{
*this = anotherList;
}
// destructor
BList::~BList()
{
free(fObjectList);
}
// =
BList&
BList::operator =(const BList &list)
{
fBlockSize = list.fBlockSize;
_ResizeArray(list.fItemCount);
fItemCount = list.fItemCount;
memcpy(fObjectList, list.fObjectList, fItemCount * sizeof(void*));
return *this;
}
// AddItem
bool
BList::AddItem(void *item, int32 index)
{
if (index < 0 || index > fItemCount)
return false;
bool result = true;
if (fItemCount + 1 > fPhysicalSize)
result = _ResizeArray(fItemCount + 1);
if (result) {
++fItemCount;
move_items(fObjectList + index, 1, fItemCount - index - 1);
fObjectList[index] = item;
}
return result;
}
// AddItem
bool
BList::AddItem(void *item)
{
bool result = true;
if (fPhysicalSize > fItemCount) {
fObjectList[fItemCount] = item;
++fItemCount;
} else {
if ((result = _ResizeArray(fItemCount + 1))) {
fObjectList[fItemCount] = item;
++fItemCount;
}
}
return result;
}
// AddList
bool
BList::AddList(const BList *list, int32 index)
{
bool result = (list && index >= 0 && index <= fItemCount);
if (result && list->fItemCount > 0) {
int32 count = list->fItemCount;
if (fItemCount + count > fPhysicalSize)
result = _ResizeArray(fItemCount + count);
if (result) {
fItemCount += count;
move_items(fObjectList + index, count, fItemCount - index - count);
memcpy(fObjectList + index, list->fObjectList,
list->fItemCount * sizeof(void *));
}
}
return result;
}
// AddList
bool
BList::AddList(const BList *list)
{
bool result = (list != NULL);
if (result && list->fItemCount > 0) {
int32 index = fItemCount;
int32 count = list->fItemCount;
if (fItemCount + count > fPhysicalSize)
result = _ResizeArray(fItemCount + count);
if (result) {
fItemCount += count;
memcpy(fObjectList + index, list->fObjectList,
list->fItemCount * sizeof(void *));
}
}
return result;
}
// RemoveItem
bool
BList::RemoveItem(void *item)
{
int32 index = IndexOf(item);
bool result = (index >= 0);
if (result)
RemoveItem(index);
return result;
}
// RemoveItem
void *
BList::RemoveItem(int32 index)
{
void *item = NULL;
if (index >= 0 && index < fItemCount) {
item = fObjectList[index];
move_items(fObjectList + index + 1, -1, fItemCount - index - 1);
--fItemCount;
if (fItemCount <= fResizeThreshold)
_ResizeArray(fItemCount);
}
return item;
}
// RemoveItems
bool
BList::RemoveItems(int32 index, int32 count)
{
bool result = (index >= 0 && index <= fItemCount);
if (result) {
if (index + count > fItemCount)
count = fItemCount - index;
if (count > 0) {
move_items(fObjectList + index + count, -count,
fItemCount - index - count);
fItemCount -= count;
if (fItemCount <= fResizeThreshold)
_ResizeArray(fItemCount);
} else
result = false;
}
return result;
}
//ReplaceItem
bool
BList::ReplaceItem(int32 index, void *newItem)
{
bool result = false;
if (index >= 0 && index < fItemCount) {
fObjectList[index] = newItem;
result = true;
}
return result;
}
// MakeEmpty
void
BList::MakeEmpty()
{
fItemCount = 0;
_ResizeArray(0);
}
/* Reordering items. */
// SortItems
void
BList::SortItems(int (*compareFunc)(const void *, const void *))
{
if (compareFunc)
qsort(fObjectList, fItemCount, sizeof(void *), compareFunc);
}
//SwapItems
bool
BList::SwapItems(int32 indexA, int32 indexB)
{
bool result = false;
if (indexA >= 0 && indexA < fItemCount
&& indexB >= 0 && indexB < fItemCount) {
void *tmpItem = fObjectList[indexA];
fObjectList[indexA] = fObjectList[indexB];
fObjectList[indexB] = tmpItem;
result = true;
}
return result;
}
//MoveItem
//This moves a list item from posititon a to position b, moving the appropriate block of
// list elements to make up for the move. For example, in the array:
// A B C D E F G H I J
// Moveing 1(B)->6(G) would result in this:
// A C D E F G B H I J
bool
BList::MoveItem(int32 fromIndex, int32 toIndex)
{
if ((fromIndex >= fItemCount) || (toIndex >= fItemCount) || (fromIndex < 0) || (toIndex < 0))
return false;
if (fromIndex < toIndex)
{
void * tmp_mover = fObjectList[fromIndex];
memmove(fObjectList + fromIndex + 1, fObjectList + fromIndex, (toIndex - fromIndex) * sizeof(void *));
fObjectList[toIndex] = tmp_mover;
}
else if (fromIndex > toIndex)
{
void * tmp_mover = fObjectList[fromIndex];
memmove(fObjectList + toIndex + 1, fObjectList + toIndex, (fromIndex - toIndex) * sizeof(void *));
fObjectList[toIndex] = tmp_mover;
};
return true;
}
/* Retrieving items. */
// ItemAt
void *
BList::ItemAt(int32 index) const
{
void *item = NULL;
if (index >= 0 && index < fItemCount)
item = fObjectList[index];
return item;
}
// FirstItem
void *
BList::FirstItem() const
{
void *item = NULL;
if (fItemCount > 0)
item = fObjectList[0];
return item;
}
// ItemAtFast
void *
BList::ItemAtFast(int32 index) const
{
return fObjectList[index];
}
// Items
void *
BList::Items() const
{
return fObjectList;
}
// LastItem
void *
BList::LastItem() const
{
void *item = NULL;
if (fItemCount > 0)
item = fObjectList[fItemCount - 1];
return item;
}
/* Querying the list. */
// HasItem
bool
BList::HasItem(void *item) const
{
return (IndexOf(item) >= 0);
}
// IndexOf
int32
BList::IndexOf(void *item) const
{
for (int32 i = 0; i < fItemCount; i++) {
if (fObjectList[i] == item)
return i;
}
return -1;
}
// CountItems
int32
BList::CountItems() const
{
return fItemCount;
}
// IsEmpty
bool
BList::IsEmpty() const
{
return (fItemCount == 0);
}
/* Iterating over the list. */
//iterate a function over the whole list. If the function outputs a true
//value, then the process is terminated.
void
BList::DoForEach(bool (*func)(void *))
{
bool terminate = false; int32 index = 0; //set terminate condition variables to go.
if (func != NULL)
{
while ((!terminate) && (index < fItemCount)) //check terminate condition.
{
terminate = func(fObjectList[index]); //reset immediate terminator
index++; //advance along the list.
};
}
}
//same as above, except this function takes an argument.
void
BList::DoForEach(bool (*func)(void *, void*), void * arg)
{
bool terminate = false; int32 index = 0;
if (func != NULL)
{
while ((!terminate) && (index < fItemCount))
{
terminate = func(fObjectList[index], arg);
index++;
};
}
}
// FBC
void BList::_ReservedList1() {}
void BList::_ReservedList2() {}
// Resize
//
// Resizes fObjectList to be large enough to contain count items.
// fItemCount is adjusted accordingly.
bool
BList::_ResizeArray(int32 count)
{
bool result = true;
// calculate the new physical size
// by doubling the existing size
// until we can hold at least count items
int32 newSize = fPhysicalSize > 0 ? fPhysicalSize : fBlockSize;
int32 targetSize = count;
if (targetSize <= 0)
targetSize = fBlockSize;
if (targetSize > fPhysicalSize) {
while (newSize < targetSize)
newSize <<= 1;
} else if (targetSize <= fResizeThreshold) {
newSize = fResizeThreshold;
}
// resize if necessary
if (newSize != fPhysicalSize) {
void** newObjectList
= (void**)realloc(fObjectList, newSize * sizeof(void*));
if (newObjectList) {
fObjectList = newObjectList;
fPhysicalSize = newSize;
// set our lower bound to either 1/4
//of the current physical size, or 0
fResizeThreshold = fPhysicalSize >> 2 >= fBlockSize
? fPhysicalSize >> 2 : 0;
} else
result = false;
}
return result;
}

View File

@ -1,288 +0,0 @@
/*
* Copyright (c) 2001-2005, Haiku, Inc.
* Distributed under the terms of the MIT license.
*
* Author: Erik Jaesler <erik@cgsoftware.com>
*/
/** Semaphore-type class for thread safety */
#include <OS.h>
#include <Locker.h>
#include <SupportDefs.h>
//
// Data Member Documentation:
//
// The "fBenaphoreCount" member is set to 1 if the BLocker style is
// semaphore. If the style is benaphore, it is initialized to 0 and
// is incremented atomically when it is acquired, decremented when it
// is released. By setting the benaphore count to 1 when the style is
// semaphore, the benaphore effectively becomes a semaphore. I was able
// to determine this is what Be's implementation does by testing the
// result of the CountLockRequests() member.
//
// The "fSemaphoreID" member holds the sem_id returned from create_sem()
// when the BLocker is constructed. It is used to acquire and release
// the lock regardless of the lock style (semaphore or benaphore).
//
// The "fLockOwner" member holds the thread_id of the thread which
// currently holds the lock. If no thread holds the lock, it is set to
// B_ERROR.
//
// The "fRecursiveCount" member holds a count of the number of times the
// thread holding the lock has acquired the lock without a matching unlock.
// It is basically the number of times the thread must call Unlock() before
// the lock can be acquired by a different thread.
//
//
// Constructors:
//
// All constructors just pass their arguments to InitLocker(). Note that
// the default for "name" is "some BLocker" and "benaphore_style" is true.
//
BLocker::BLocker()
{
InitLocker(NULL, true);
}
BLocker::BLocker(const char *name)
{
InitLocker(name, true);
}
BLocker::BLocker(bool benaphoreStyle)
{
InitLocker(NULL, benaphoreStyle);
}
BLocker::BLocker(const char *name, bool benaphoreStyle)
{
InitLocker(name, benaphoreStyle);
}
//
// This constructor is not documented. The final argument is ignored for
// now. In Be's headers, its called "for_IPC". DO NOT USE THIS
// CONSTRUCTOR!
//
BLocker::BLocker(const char *name, bool benaphoreStyle,
bool)
{
InitLocker(name, benaphoreStyle);
}
//
// The destructor just deletes the semaphore. By deleting the semaphore,
// any threads waiting to acquire the BLocker will be unblocked.
//
BLocker::~BLocker()
{
delete_sem(fSemaphoreID);
}
bool
BLocker::Lock(void)
{
status_t result;
return AcquireLock(B_INFINITE_TIMEOUT, &result);
}
status_t
BLocker::LockWithTimeout(bigtime_t timeout)
{
status_t result;
AcquireLock(timeout, &result);
return result;
}
void
BLocker::Unlock(void)
{
// If the thread currently holds the lockdecrement
if (IsLocked()) {
// Decrement the number of outstanding locks this thread holds
// on this BLocker.
fRecursiveCount--;
// If the recursive count is now at 0, that means the BLocker has
// been released by the thread.
if (fRecursiveCount == 0) {
// The BLocker is no longer owned by any thread.
fLockOwner = B_ERROR;
// Decrement the benaphore count and store the undecremented
// value in oldBenaphoreCount.
int32 oldBenaphoreCount = atomic_add(&fBenaphoreCount, -1);
// If the oldBenaphoreCount is greater than 1, then there is
// at lease one thread waiting for the lock in the case of a
// benaphore.
if (oldBenaphoreCount > 1) {
// Since there are threads waiting for the lock, it must
// be released. Note, the old benaphore count will always be
// greater than 1 for a semaphore so the release is always done.
release_sem(fSemaphoreID);
}
}
}
}
thread_id
BLocker::LockingThread(void) const
{
return fLockOwner;
}
bool
BLocker::IsLocked(void) const
{
// This member returns true if the calling thread holds the lock.
// The easiest way to determine this is to compare the result of
// find_thread() to the fLockOwner.
return find_thread(NULL) == fLockOwner;
}
int32
BLocker::CountLocks(void) const
{
return fRecursiveCount;
}
int32
BLocker::CountLockRequests(void) const
{
return fBenaphoreCount;
}
sem_id
BLocker::Sem(void) const
{
return fSemaphoreID;
}
void
BLocker::InitLocker(const char *name, bool benaphore)
{
if (name == NULL)
name = "some BLocker";
if (benaphore) {
// Because this is a benaphore, initialize the benaphore count and
// create the semaphore. Because this is a benaphore, the semaphore
// count starts at 0 (ie acquired).
fBenaphoreCount = 0;
fSemaphoreID = create_sem(0, name);
} else {
// Because this is a semaphore, initialize the benaphore count to -1
// and create the semaphore. Because this is semaphore style, the
// semaphore count starts at 1 so that one thread can acquire it and
// the next thread to acquire it will block.
fBenaphoreCount = 1;
fSemaphoreID = create_sem(1, name);
}
// The lock is currently not acquired so there is no owner.
fLockOwner = B_ERROR;
// The lock is currently not acquired so the recursive count is zero.
fRecursiveCount = 0;
}
bool
BLocker::AcquireLock(bigtime_t timeout, status_t *error)
{
// By default, return no error.
status_t status = B_OK;
// Only try to acquire the lock if the thread doesn't already own it.
if (!IsLocked()) {
// Increment the benaphore count and test to see if it was already greater
// than 0. If it is greater than 0, then some thread already has the
// benaphore or the style is a semaphore. Either way, we need to acquire
// the semaphore in this case.
int32 oldBenaphoreCount = atomic_add(&fBenaphoreCount, 1);
if (oldBenaphoreCount > 0) {
do {
status = acquire_sem_etc(fSemaphoreID, 1, B_RELATIVE_TIMEOUT,
timeout);
} while (status == B_INTERRUPTED);
// Note, if the lock here does time out, the benaphore count
// is not decremented. By doing this, the benaphore count will
// never go back to zero. This means that the locking essentially
// changes to semaphore style if this was a benaphore.
//
// Doing the decrement of the benaphore count when the acquisition
// fails is a risky thing to do. If you decrement the counter at
// the same time the thread which holds the benaphore does an
// Unlock(), there is serious risk of a race condition.
//
// If the Unlock() sees a positive count and releases the semaphore
// and then the timed out thread decrements the count to 0, there
// is no one to take the semaphore. The next two threads will be
// able to acquire the benaphore at the same time! The first will
// increment the counter and acquire the lock. The second will
// acquire the semaphore and therefore the lock. Not good.
//
// This has been discussed on the becodetalk mailing list and
// Trey from Be had this to say:
//
// I looked at the LockWithTimeout() code, and it does not have
// _this_ (ie the race condition) problem. It circumvents it by
// NOT doing the atomic_add(&count, -1) if the semaphore
// acquisition fails. This means that if a
// BLocker::LockWithTimeout() times out, all other Lock*() attempts
// turn into guaranteed semaphore grabs, _with_ the overhead of a
// (now) useless atomic_add().
//
// Given Trey's comments, it looks like Be took the same approach
// I did. The output of CountLockRequests() of Be's implementation
// confirms Trey's comments also.
//
// Finally some thoughts for the future with this code:
// - If 2^31 timeouts occur on a 32-bit machine (ie today),
// the benaphore count will wrap to a negative number. This
// would have unknown consequences on the ability of the BLocker
// to continue to function.
//
}
}
// If the lock has successfully been acquired.
if (status == B_OK) {
// Set the lock owner to this thread and increment the recursive count
// by one. The recursive count is incremented because one more Unlock()
// is now required to release the lock (ie, 0 => 1, 1 => 2 etc).
fLockOwner = find_thread(NULL);
fRecursiveCount++;
}
if (error != NULL)
*error = status;
// Return true if the lock has been acquired.
return (status == B_OK);
}

View File

@ -1,589 +0,0 @@
/*
** Copyright 2003-2004, Stefano Ceccherini (burton666@libero.it). All rights reserved.
** 2004, Michael Pfeiffer (laplace@users.sourceforge.net).
** Distributed under the terms of the Haiku License.
**
** History
** 2003-2004 Initial implementation by Stefano Ceccerini.
** 2004/08/03 Testing, bug fixing and implementation of quick sort, refactoring
** by Michael Pfeiffer.
*/
// TODO:
// - Rewrite to use STL
// - Include ObjectList.h
// - Test if building with jam works
// Note: Method Owning() is inlined in header file ObjectList.h
#include <algorithm>
#include <functional>
#include <assert.h>
#include <List.h>
// If USE_STL is 1 binary search and sort are used from STL.
// The implementation of _PointerList_ should be completely rewritten to
// use STL in a more efficent way!
#define USE_STL 1
using namespace std;
// Declaration of class _PointerList_ is inlined to be independent of the
// header file ObjectList.h
#ifndef __OBJECT_LIST__
class _PointerList_ : public BList {
public:
_PointerList_(const _PointerList_ &list);
_PointerList_(int32 itemsPerBlock = 20, bool owning = false);
~_PointerList_();
typedef void *(* GenericEachFunction)(void *item, void *arg);
typedef int (* GenericCompareFunction)(const void *key, const void *item);
typedef int (* GenericCompareFunctionWithState)(const void *key, const void *item,
void *state);
typedef int (* UnaryPredicateGlue)(const void *item, void *key);
void *EachElement(GenericEachFunction, void *arg);
void SortItems(GenericCompareFunction);
void SortItems(GenericCompareFunctionWithState, void *state);
void HSortItems(GenericCompareFunction);
void HSortItems(GenericCompareFunctionWithState, void *state);
void *BinarySearch(const void *key, GenericCompareFunction) const;
void *BinarySearch(const void *key, GenericCompareFunctionWithState, void *state) const;
int32 BinarySearchIndex(const void *key, GenericCompareFunction) const;
int32 BinarySearchIndex(const void *key, GenericCompareFunctionWithState, void *state) const;
int32 BinarySearchIndexByPredicate(const void *arg, UnaryPredicateGlue) const;
bool Owning() const;
bool ReplaceItem(int32, void *);
protected:
bool owning;
};
#endif
struct comparator;
class AbstractPointerListHelper {
public:
AbstractPointerListHelper() {};
virtual ~AbstractPointerListHelper();
/**
Returns the index of the item that matches key or
a negative number. Then -(index+1) is the insert position
of the item not in list.
*/
int32 BinarySearchIndex(const void *key, const BList *list);
/**
Returns the item that matches key or NULL if the item could
not be found in the list.
*/
void* BinarySearch(const void *key, const BList *list);
/**
Sorts the items in list.
*/
void SortItems(BList *list);
/**
Removes the first item in list and appends it at the bottom of
the list and sorts all items but the last item.
*/
void HSortItems(BList *list);
#if USE_STL
friend struct comparator;
#endif
private:
enum {
// Use insertion sort if number of elements in list is less than
// kQuickSortThreshold.
kQuickSortThreshold = 11,
// Use simple pivot element computation if number of elements in
// list is less than kPivotThreshold.
kPivotThreshold = 5,
};
// Methods that do the actual work:
inline void Swap(void **items, int32 i, int32 j);
void* BinarySearch(const void *key, const void **items, int32 numItems, int32 &index);
#if !USE_STL
void InsertionSort(void **items, int32 numItems);
inline void InsertionSort(void **items, int32 low, int32 high);
int32 ChoosePivot(void **items, int32 low, int32 high);
int32 Partition(void **items, int32 low, int32 high, bool &isSorted);
#endif
void QuickSort(void **items, int32 low, int32 high);
// Method to be implemented by sub classes
int virtual Compare(const void *key, const void* item) = 0;
};
#if USE_STL
struct comparator : public binary_function<const void*, const void*, bool>
{
comparator(AbstractPointerListHelper* helper) : helper(helper) {}
bool operator()(const void* a, const void* b) {
return helper->Compare(b, a) > 0;
}
AbstractPointerListHelper* helper;
};
#endif
AbstractPointerListHelper::~AbstractPointerListHelper()
{
}
void
AbstractPointerListHelper::Swap(void **items, int32 i, int32 j)
{
void *swap = items[i];
items[i] = items[j];
items[j] = swap;
}
int32
AbstractPointerListHelper::BinarySearchIndex(const void *key, const BList *list)
{
int32 index;
const void **items = static_cast<const void**>(list->Items());
BinarySearch(key, items, list->CountItems(), index);
return index;
}
void *
AbstractPointerListHelper::BinarySearch(const void *key, const BList *list)
{
int32 index;
const void **items = static_cast<const void**>(list->Items());
return BinarySearch(key, items, list->CountItems(), index);
}
void
AbstractPointerListHelper::SortItems(BList *list)
{
void **items = static_cast<void**>(list->Items());
QuickSort(items, 0, list->CountItems()-1);
}
void
AbstractPointerListHelper::HSortItems(BList *list)
{
void **items = static_cast<void**>(list->Items());
int32 numItems = list->CountItems();
if (numItems > 1) {
// swap last with first item
Swap(items, 0, numItems-1);
}
// sort all items but last item
QuickSort(items, 0, numItems-2);
}
void *
AbstractPointerListHelper::BinarySearch(const void *key, const void **items, int32 numItems, int32 &index)
{
#if USE_STL
const void** end = &items[numItems];
const void** found = lower_bound(items, end, key, comparator(this));
index = found - items;
if (index != numItems && Compare(key, *found) == 0) {
return const_cast<void*>(*found);
} else {
index = -(index + 1);
return NULL;
}
#else
int32 low = 0;
int32 high = numItems-1;
int result = 0;
index = 0;
while (low <= high) {
index = (low + high) / 2;
const void *item = items[index];
result = Compare(key, item);
if (result < 0) {
// key < item
high = index - 1;
} else if (result > 0) {
// key > item
low = index + 1;
} else {
// key == item
return const_cast<void *>(item);
}
}
// item not found
if (result > 0) {
// key > last item (= items[index])
// insert position for key is after last item
index ++;
}
index = -(index+1);
return NULL;
#endif
}
#if !USE_STL
int32
AbstractPointerListHelper::ChoosePivot(void **items, int32 low, int32 high)
{
if (kPivotThreshold <= kQuickSortThreshold
|| high - low > kPivotThreshold) {
assert(high - low > kPivotThreshold);
// choose the middle item of three items
int32 mid = (low + high) / 2;
void* first = items[low];
void* middle = items[mid];
void* last = items[high];
if (Compare(first, middle) <= 0) {
// first <= middle
if (Compare(middle, last) <= 0) {
// first <= middle <= last
return mid;
}
// first <= middle and last < middle
if (Compare(first, last) <= 0) {
// first <= last < middle
return high;
}
// last < first <= middle
return low;
}
// middle < first
if (Compare(first, last) <= 0) {
// middle < first <= last
return low;
}
// middle < first and last < first
if (Compare(middle, last) <= 0) {
// middle <= last < first
return high;
}
// last < middle < first
return mid;
} else {
// choose the middle element to avoid O(n^2) for an already sorted list
return (low + high) / 2;
}
}
int32
AbstractPointerListHelper::Partition(void **items, int32 low, int32 high, bool &isSorted)
{
assert(low < high);
int32 left = low;
int32 right = high;
int32 pivot = ChoosePivot(items, low, high);
void *pivotItem = items[pivot];
// Optimization: Check if all items are equal. We get this almost for free.
// Searching the first item that does not belong to the left list has to
// be done anyway.
int32 result;
isSorted = true;
// Search first item in left part that does not belong to this part
// (where item > pivotItem)
while (left < right && (result = Compare(items[left], pivotItem)) <= 0) {
left ++;
if (result != 0) {
isSorted = false;
break;
}
}
if (isSorted && left == right && Compare(items[right], pivotItem) == 0) {
return low;
}
// End of optimization
isSorted = false;
// pivot element has to be first element in list
if (low != pivot)
Swap(items, low, pivot);
// now partion the array in a left part where item <= pivotItem
// and a right part where item > pivotItem
do {
// search first item in left part that does not belong to this part
// (where item > pivotItem)
while (left < right && Compare(items[left], pivotItem) <= 0) {
left ++;
}
// search first item (from right to left) in right part that does not belong
// to this part (where item <= pivotItem). This holds at least for pivot
// element at top of list! No array bounds check needed!
while (Compare(items[right], pivotItem) > 0) {
right --;
}
if (left < right) {
// now swap the items to the proper part
Swap(items, left, right);
}
} while (left < right);
// place pivotItem between left and right part
items[low] = items[right];
items[right] = pivotItem;
return right;
}
void
AbstractPointerListHelper::InsertionSort(void **items, int32 numItems)
{
for (int32 i = 1; i < numItems; i ++) {
// treat list[0 .. i-1] as sorted
void* item = items[i];
// insert item at right place in list[0..i]
int32 j = i;
void* prev = items[j-1];
while (Compare(prev, item) > 0) {
items[j] = prev;
j --;
if (j <= 0) break;
prev = items[j-1];
}
items[j] = item;
}
}
void
AbstractPointerListHelper::InsertionSort(void **items, int32 low, int32 high)
{
InsertionSort(&items[low], high - low + 1);
}
#endif
void
AbstractPointerListHelper::QuickSort(void **items, int32 low, int32 high)
{
#if USE_STL
if (low <= high) {
sort(&items[low], &items[high+1], comparator(this));
}
#else
if (low < high) {
if (high - low < kQuickSortThreshold) {
InsertionSort(items, low, high);
} else {
bool isSorted;
int pivot = Partition(items, low, high, isSorted);
if (isSorted) return;
QuickSort(items, low, pivot - 1);
QuickSort(items, pivot + 1, high);
}
}
#endif
}
class PointerListHelper : public AbstractPointerListHelper {
public:
PointerListHelper(_PointerList_::GenericCompareFunction compareFunc)
: fCompareFunc(compareFunc)
{
// nothing to do
}
int Compare(const void *a, const void *b)
{
return fCompareFunc(a, b);
}
private:
_PointerList_::GenericCompareFunction fCompareFunc;
};
class PointerListHelperWithState : public AbstractPointerListHelper
{
public:
PointerListHelperWithState(
_PointerList_::GenericCompareFunctionWithState compareFunc,
void* state)
: fCompareFunc(compareFunc)
, fState(state)
{
// nothing to do
}
int Compare(const void *a, const void *b)
{
return fCompareFunc(a, b, fState);
}
private:
_PointerList_::GenericCompareFunctionWithState fCompareFunc;
void* fState;
};
class PointerListHelperUsePredicate : public AbstractPointerListHelper
{
public:
PointerListHelperUsePredicate(
_PointerList_::UnaryPredicateGlue predicate)
: fPredicate(predicate)
{
// nothing to do
}
int Compare(const void *arg, const void *item)
{
// need to adapt arguments and return value
return -fPredicate(item, const_cast<void *>(arg));
}
private:
_PointerList_::UnaryPredicateGlue fPredicate;
};
// Implementation of class _PointerList_
_PointerList_::_PointerList_(int32 itemsPerBlock, bool own)
:
BList(itemsPerBlock),
owning(own)
{
}
_PointerList_::_PointerList_(const _PointerList_ &list)
:
BList(list),
owning(list.owning)
{
}
_PointerList_::~_PointerList_()
{
// This is empty by design, the "owning" variable
// is used by the BObjectList subclass
}
// Note: function pointers must not be NULL!!!
void *
_PointerList_::EachElement(GenericEachFunction function, void *arg)
{
int32 numItems = CountItems();
void *result = NULL;
for (int32 index = 0; index < numItems; index++) {
result = function(ItemAtFast(index), arg);
if (result != NULL)
break;
}
return result;
}
void
_PointerList_::SortItems(GenericCompareFunction compareFunc)
{
PointerListHelper helper(compareFunc);
helper.SortItems(this);
}
void
_PointerList_::SortItems(GenericCompareFunctionWithState compareFunc, void *state)
{
PointerListHelperWithState helper(compareFunc, state);
helper.SortItems(this);
}
void
_PointerList_::HSortItems(GenericCompareFunction compareFunc)
{
PointerListHelper helper(compareFunc);
helper.HSortItems(this);
}
void
_PointerList_::HSortItems(GenericCompareFunctionWithState compareFunc, void *state)
{
PointerListHelperWithState helper(compareFunc, state);
helper.HSortItems(this);
}
void *
_PointerList_::BinarySearch(const void *key, GenericCompareFunction compareFunc) const
{
PointerListHelper helper(compareFunc);
return helper.BinarySearch(key, this);
}
void *
_PointerList_::BinarySearch(const void *key,
GenericCompareFunctionWithState compareFunc, void *state) const
{
PointerListHelperWithState helper(compareFunc, state);
return helper.BinarySearch(key, this);
}
int32
_PointerList_::BinarySearchIndex(const void *key, GenericCompareFunction compareFunc) const
{
PointerListHelper helper(compareFunc);
return helper.BinarySearchIndex(key, this);
}
int32
_PointerList_::BinarySearchIndex(const void *key,
GenericCompareFunctionWithState compareFunc, void *state) const
{
PointerListHelperWithState helper(compareFunc, state);
return helper.BinarySearchIndex(key, this);
}
int32
_PointerList_::BinarySearchIndexByPredicate(const void *key, UnaryPredicateGlue predicate) const
{
PointerListHelperUsePredicate helper(predicate);
return helper.BinarySearchIndex(key, this);
}
bool
_PointerList_::ReplaceItem(int32 index, void *newItem)
{
if (index < 0 || index >= CountItems())
return false;
void **items = static_cast<void **>(Items());
items[index] = newItem;
return true;
}

View File

@ -1,123 +0,0 @@
//------------------------------------------------------------------------------
// Copyright (c) 2001-2004, OpenBeOS
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// File Name: StopWatch.cpp
// Author(s): unknown
//
// Description: Timer Class, mostly useful for debugging
//
//
//
//------------------------------------------------------------------------------
#include <OS.h> // for system_time()
#include <StopWatch.h>
#include <stdio.h>
BStopWatch::BStopWatch(const char *name, bool silent)
:
fName(name),
fSilent(silent)
{
Reset();
}
BStopWatch::~BStopWatch()
{
if (!fSilent){
printf("StopWatch \"%s\": %d usecs.\n", fName, (int)ElapsedTime());
if (fLap) {
for (int i = 1; i <= fLap; i++){
if (!((i-1)%4))
printf("\n ");
printf("[%d: %d#%d] ", i, (int)(fLaps[i]-fStart), (int)(fLaps[i] - fLaps[i -1 ]));
}
printf("\n");
}
}
}
void
BStopWatch::Suspend()
{
if (!fSuspendTime)
fSuspendTime = system_time();
}
void
BStopWatch::Resume()
{
if (fSuspendTime)
fStart = system_time() - fSuspendTime - fStart;
}
bigtime_t
BStopWatch::Lap()
{
if (!fSuspendTime){
if (fLap<9)
fLap++;
fLaps[fLap] = system_time();
return system_time() - fStart;
} else
return 0;
}
bigtime_t
BStopWatch::ElapsedTime() const
{
if (fSuspendTime)
return fSuspendTime - fStart;
else
return system_time() - fStart;
}
void
BStopWatch::Reset()
{
fStart = system_time(); // store current time
fSuspendTime = 0;
fLap = 0; // clear laps
for (int i = 0; i < 10; i++)
fLaps[i] = fStart;
}
const char *
BStopWatch::Name() const
{
return fName != NULL ? fName : "";
}
// just for future binary compatibility
void BStopWatch::_ReservedStopWatch1() {}
void BStopWatch::_ReservedStopWatch2() {}

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,7 @@ SubDir HAIKU_TOP src build libroot ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os app ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os drivers ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os kernel ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os interface ] : true ;
UseHeaders [ FDirName $(HAIKU_TOP) headers build os storage ] : true ;
@ -18,6 +19,9 @@ UsePrivateBuildHeaders kernel ;
SubDirC++Flags $(defines) ;
}
DEFINES += KMESSAGE_CONTAINER_ONLY ;
ObjectC++Flags KMessage.cpp : $(HOST_BE_API_C++FLAGS) ;
# locate the library
MakeLocate libroot_build.so : $(HOST_BUILD_COMPATIBILITY_LIB_DIR) ;
@ -51,6 +55,8 @@ local librootSources =
$(strlSources)
strnlen.c
KMessage.cpp
;
BuildPlatformSharedLibrary libroot_build.so :
@ -66,3 +72,5 @@ BuildPlatformStaticLibrary libroot_build.a :
SEARCH on [ FGristFiles $(strlSources) strnlen.c ]
= [ FDirName $(HAIKU_TOP) src system libroot posix string ] ;
SEARCH on [ FGristFiles KMessage.cpp ]
= [ FDirName $(HAIKU_TOP) src system kernel messaging ] ;