Refactored and cleaned up smart pointers.

This commit is contained in:
Vincent Richard 2006-03-29 20:06:39 +00:00
parent 0396b85db1
commit e9501b48d8
34 changed files with 934 additions and 735 deletions

View File

@ -149,7 +149,7 @@ libvmime_sources = [
'utility/path.cpp', 'utility/path.hpp', 'utility/path.cpp', 'utility/path.hpp',
'utility/progressListener.cpp', 'utility/progressListener.hpp', 'utility/progressListener.cpp', 'utility/progressListener.hpp',
'utility/random.cpp', 'utility/random.hpp', 'utility/random.cpp', 'utility/random.hpp',
'utility/smartPtr.hpp', 'utility/smartPtr.cpp', 'utility/smartPtr.hpp',
'utility/stream.cpp', 'utility/stream.hpp', 'utility/stream.cpp', 'utility/stream.hpp',
'utility/stringProxy.cpp', 'utility/stringProxy.hpp', 'utility/stringProxy.cpp', 'utility/stringProxy.hpp',
'utility/stringUtils.cpp', 'utility/stringUtils.hpp', 'utility/stringUtils.cpp', 'utility/stringUtils.hpp',

View File

@ -64,7 +64,7 @@ void body::parse(const string& buffer, const string::size_type position,
try try
{ {
const ref <const contentTypeField> ctf = const ref <const contentTypeField> ctf =
m_header->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>(); m_header.acquire()->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>();
const mediaType type = *ctf->getValue().dynamicCast <const mediaType>(); const mediaType type = *ctf->getValue().dynamicCast <const mediaType>();
@ -211,7 +211,7 @@ void body::generate(utility::outputStream& os, const string::size_type maxLineLe
{ {
string boundary; string boundary;
if (m_header == NULL) if (m_header.acquire() == NULL)
{ {
boundary = generateRandomBoundaryString(); boundary = generateRandomBoundaryString();
} }
@ -220,7 +220,8 @@ void body::generate(utility::outputStream& os, const string::size_type maxLineLe
try try
{ {
ref <const contentTypeField> ctf = ref <const contentTypeField> ctf =
m_header->findField(fields::CONTENT_TYPE).dynamicCast <const contentTypeField>(); m_header.acquire()->findField(fields::CONTENT_TYPE)
.dynamicCast <const contentTypeField>();
boundary = ctf->getBoundary(); boundary = ctf->getBoundary();
} }
@ -389,7 +390,7 @@ const mediaType body::getContentType() const
try try
{ {
ref <const contentTypeField> ctf = ref <const contentTypeField> ctf =
m_header->findField(fields::CONTENT_TYPE).dynamicCast <const contentTypeField>(); m_header.acquire()->findField(fields::CONTENT_TYPE).dynamicCast <const contentTypeField>();
return (*ctf->getValue().dynamicCast <const mediaType>()); return (*ctf->getValue().dynamicCast <const mediaType>());
} }
@ -406,7 +407,7 @@ const charset body::getCharset() const
try try
{ {
const ref <const contentTypeField> ctf = const ref <const contentTypeField> ctf =
m_header->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>(); m_header.acquire()->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>();
return (ctf->getCharset()); return (ctf->getCharset());
} }
@ -428,7 +429,7 @@ const encoding body::getEncoding() const
try try
{ {
const ref <const headerField> cef = const ref <const headerField> cef =
m_header->findField(fields::CONTENT_TRANSFER_ENCODING); m_header.acquire()->findField(fields::CONTENT_TRANSFER_ENCODING);
return (*cef->getValue().dynamicCast <const encoding>()); return (*cef->getValue().dynamicCast <const encoding>());
} }
@ -440,7 +441,7 @@ const encoding body::getEncoding() const
} }
void body::setParentPart(weak_ref <bodyPart> parent) void body::setParentPart(ref <bodyPart> parent)
{ {
m_part = parent; m_part = parent;
m_header = (parent != NULL ? parent->getHeader() : NULL); m_header = (parent != NULL ? parent->getHeader() : NULL);
@ -449,7 +450,8 @@ void body::setParentPart(weak_ref <bodyPart> parent)
const bool body::isRootPart() const const bool body::isRootPart() const
{ {
return (m_part == NULL || m_part->getParentPart() == NULL); ref <const bodyPart> part = m_part.acquire();
return (part == NULL || part->getParentPart() == NULL);
} }
@ -532,13 +534,15 @@ void body::initNewPart(ref <bodyPart> part)
{ {
part->m_parent = m_part; part->m_parent = m_part;
if (m_header != NULL) ref <header> hdr = m_header.acquire();
if (hdr != NULL)
{ {
// Check whether we have a boundary string // Check whether we have a boundary string
try try
{ {
ref <contentTypeField> ctf = ref <contentTypeField> ctf =
m_header->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>(); hdr->findField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>();
try try
{ {
@ -564,7 +568,7 @@ void body::initNewPart(ref <bodyPart> part)
// No "Content-Type" field: create a new one and generate // No "Content-Type" field: create a new one and generate
// a random boundary string. // a random boundary string.
ref <contentTypeField> ctf = ref <contentTypeField> ctf =
m_header->getField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>(); hdr->getField(fields::CONTENT_TYPE).dynamicCast <contentTypeField>();
ctf->setValue(mediaType(mediaTypes::MULTIPART, mediaTypes::MULTIPART_MIXED)); ctf->setValue(mediaType(mediaTypes::MULTIPART, mediaTypes::MULTIPART_MIXED));
ctf->setBoundary(generateRandomBoundaryString()); ctf->setBoundary(generateRandomBoundaryString());

View File

@ -33,7 +33,7 @@ bodyPart::bodyPart()
m_body(vmime::create <body>()), m_body(vmime::create <body>()),
m_parent(NULL) m_parent(NULL)
{ {
m_body->setParentPart(this); m_body->setParentPart(thisRef().dynamicCast <bodyPart>());
} }
@ -121,9 +121,15 @@ ref <body> bodyPart::getBody()
} }
weak_ref <bodyPart> bodyPart::getParentPart() const ref <bodyPart> bodyPart::getParentPart()
{ {
return (m_parent); return m_parent.acquire();
}
ref <const bodyPart> bodyPart::getParentPart() const
{
return m_parent.acquire();
} }

View File

@ -41,11 +41,11 @@
// Helpers for service properties // Helpers for service properties
#define GET_PROPERTY(type, prop) \ #define GET_PROPERTY(type, prop) \
(m_store->getInfos().getPropertyValue <type>(getSession(), \ (m_store.acquire()->getInfos().getPropertyValue <type>(getSession(), \
dynamic_cast <const IMAPServiceInfos&>(m_store->getInfos()).getProperties().prop)) dynamic_cast <const IMAPServiceInfos&>(m_store.acquire()->getInfos()).getProperties().prop))
#define HAS_PROPERTY(prop) \ #define HAS_PROPERTY(prop) \
(m_store->getInfos().hasProperty(getSession(), \ (m_store.acquire()->getInfos().hasProperty(getSession(), \
dynamic_cast <const IMAPServiceInfos&>(m_store->getInfos()).getProperties().prop)) dynamic_cast <const IMAPServiceInfos&>(m_store.acquire()->getInfos()).getProperties().prop))
namespace vmime { namespace vmime {
@ -53,7 +53,7 @@ namespace net {
namespace imap { namespace imap {
IMAPConnection::IMAPConnection(weak_ref <IMAPStore> store, ref <security::authenticator> auth) IMAPConnection::IMAPConnection(ref <IMAPStore> store, ref <security::authenticator> auth)
: m_store(store), m_auth(auth), m_socket(NULL), m_parser(NULL), m_tag(NULL), : m_store(store), m_auth(auth), m_socket(NULL), m_parser(NULL), m_tag(NULL),
m_hierarchySeparator('\0'), m_state(STATE_NONE), m_timeoutHandler(NULL), m_hierarchySeparator('\0'), m_state(STATE_NONE), m_timeoutHandler(NULL),
m_secured(false) m_secured(false)
@ -88,18 +88,20 @@ void IMAPConnection::connect()
const string address = GET_PROPERTY(string, PROPERTY_SERVER_ADDRESS); const string address = GET_PROPERTY(string, PROPERTY_SERVER_ADDRESS);
const port_t port = GET_PROPERTY(port_t, PROPERTY_SERVER_PORT); const port_t port = GET_PROPERTY(port_t, PROPERTY_SERVER_PORT);
ref <IMAPStore> store = m_store.acquire();
// Create the time-out handler // Create the time-out handler
if (m_store->getTimeoutHandlerFactory()) if (store->getTimeoutHandlerFactory())
m_timeoutHandler = m_store->getTimeoutHandlerFactory()->create(); m_timeoutHandler = store->getTimeoutHandlerFactory()->create();
// Create and connect the socket // Create and connect the socket
m_socket = m_store->getSocketFactory()->create(); m_socket = store->getSocketFactory()->create();
#if VMIME_HAVE_TLS_SUPPORT #if VMIME_HAVE_TLS_SUPPORT
if (m_store->isIMAPS()) // dedicated port/IMAPS if (store->isIMAPS()) // dedicated port/IMAPS
{ {
ref <tls::TLSSession> tlsSession = ref <tls::TLSSession> tlsSession =
vmime::create <tls::TLSSession>(m_store->getCertificateVerifier()); vmime::create <tls::TLSSession>(store->getCertificateVerifier());
ref <tls::TLSSocket> tlsSocket = ref <tls::TLSSocket> tlsSocket =
tlsSession->getSocket(m_socket); tlsSession->getSocket(m_socket);
@ -150,7 +152,7 @@ void IMAPConnection::connect()
const bool tlsRequired = HAS_PROPERTY(PROPERTY_CONNECTION_TLS_REQUIRED) const bool tlsRequired = HAS_PROPERTY(PROPERTY_CONNECTION_TLS_REQUIRED)
&& GET_PROPERTY(bool, PROPERTY_CONNECTION_TLS_REQUIRED); && GET_PROPERTY(bool, PROPERTY_CONNECTION_TLS_REQUIRED);
if (!m_store->isSecuredConnection() && tls) // only if not IMAPS if (!store->isSecuredConnection() && tls) // only if not IMAPS
{ {
try try
{ {
@ -202,7 +204,7 @@ void IMAPConnection::connect()
void IMAPConnection::authenticate() void IMAPConnection::authenticate()
{ {
getAuthenticator()->setService(m_store.toStrong()); getAuthenticator()->setService(m_store.acquire());
#if VMIME_HAVE_SASL_SUPPORT #if VMIME_HAVE_SASL_SUPPORT
// First, try SASL authentication // First, try SASL authentication
@ -448,7 +450,7 @@ void IMAPConnection::startTLS()
} }
ref <tls::TLSSession> tlsSession = ref <tls::TLSSession> tlsSession =
vmime::create <tls::TLSSession>(m_store->getCertificateVerifier()); vmime::create <tls::TLSSession>(m_store.acquire()->getCertificateVerifier());
ref <tls::TLSSocket> tlsSocket = ref <tls::TLSSocket> tlsSocket =
tlsSession->getSocket(m_socket); tlsSession->getSocket(m_socket);
@ -693,21 +695,21 @@ ref <const IMAPParser> IMAPConnection::getParser() const
} }
weak_ref <const IMAPStore> IMAPConnection::getStore() const ref <const IMAPStore> IMAPConnection::getStore() const
{ {
return (m_store); return m_store.acquire();
} }
weak_ref <IMAPStore> IMAPConnection::getStore() ref <IMAPStore> IMAPConnection::getStore()
{ {
return (m_store); return m_store.acquire();
} }
ref <session> IMAPConnection::getSession() ref <session> IMAPConnection::getSession()
{ {
return (m_store->getSession()); return m_store.acquire()->getSession();
} }

View File

@ -39,23 +39,25 @@ namespace net {
namespace imap { namespace imap {
IMAPFolder::IMAPFolder(const folder::path& path, IMAPStore* store, const int type, const int flags) IMAPFolder::IMAPFolder(const folder::path& path, ref <IMAPStore> store, const int type, const int flags)
: m_store(store), m_connection(m_store->connection()), m_path(path), : m_store(store), m_connection(store->connection()), m_path(path),
m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()), m_mode(-1), m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()), m_mode(-1),
m_open(false), m_type(type), m_flags(flags), m_messageCount(0), m_uidValidity(0) m_open(false), m_type(type), m_flags(flags), m_messageCount(0), m_uidValidity(0)
{ {
m_store->registerFolder(this); store->registerFolder(this);
} }
IMAPFolder::~IMAPFolder() IMAPFolder::~IMAPFolder()
{ {
if (m_store) ref <IMAPStore> store = m_store.acquire();
if (store)
{ {
if (m_open) if (m_open)
close(false); close(false);
m_store->unregisterFolder(this); store->unregisterFolder(this);
} }
else if (m_open) else if (m_open)
{ {
@ -128,12 +130,14 @@ const folder::path IMAPFolder::getFullPath() const
void IMAPFolder::open(const int mode, bool failIfModeIsNotAvailable) void IMAPFolder::open(const int mode, bool failIfModeIsNotAvailable)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
// Open a connection for this folder // Open a connection for this folder
ref <IMAPConnection> connection = ref <IMAPConnection> connection =
vmime::create <IMAPConnection>(m_store, m_store->getAuthenticator()); vmime::create <IMAPConnection>(store, store->getAuthenticator());
try try
{ {
@ -270,7 +274,9 @@ void IMAPFolder::open(const int mode, bool failIfModeIsNotAvailable)
void IMAPFolder::close(const bool expunge) void IMAPFolder::close(const bool expunge)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (!isOpen()) if (!isOpen())
@ -292,7 +298,7 @@ void IMAPFolder::close(const bool expunge)
oldConnection->disconnect(); oldConnection->disconnect();
// Now use default store connection // Now use default store connection
m_connection = m_store->connection(); m_connection = m_store.acquire()->connection();
m_open = false; m_open = false;
m_mode = -1; m_mode = -1;
@ -317,13 +323,15 @@ void IMAPFolder::onClose()
void IMAPFolder::create(const int type) void IMAPFolder::create(const int type)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (isOpen()) else if (isOpen())
throw exceptions::illegal_state("Folder is open"); throw exceptions::illegal_state("Folder is open");
else if (exists()) else if (exists())
throw exceptions::illegal_state("Folder already exists"); throw exceptions::illegal_state("Folder already exists");
else if (!m_store->isValidFolderName(m_name)) else if (!store->isValidFolderName(m_name))
throw exceptions::invalid_folder_name(); throw exceptions::invalid_folder_name();
// Emit the "CREATE" command // Emit the "CREATE" command
@ -365,7 +373,9 @@ void IMAPFolder::create(const int type)
const bool IMAPFolder::exists() const bool IMAPFolder::exists()
{ {
if (!isOpen() && !m_store) ref <IMAPStore> store = m_store.acquire();
if (!isOpen() && !store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
return (testExistAndGetType() != TYPE_UNDEFINED); return (testExistAndGetType() != TYPE_UNDEFINED);
@ -458,7 +468,7 @@ ref <message> IMAPFolder::getMessage(const int num)
if (num < 1 || num > m_messageCount) if (num < 1 || num > m_messageCount)
throw exceptions::message_not_found(); throw exceptions::message_not_found();
return vmime::create <IMAPMessage>(this, num); return vmime::create <IMAPMessage>(thisRef().dynamicCast <IMAPFolder>(), num);
} }
@ -473,9 +483,10 @@ std::vector <ref <message> > IMAPFolder::getMessages(const int from, const int t
throw exceptions::message_not_found(); throw exceptions::message_not_found();
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <IMAPFolder> thisFolder = thisRef().dynamicCast <IMAPFolder>();
for (int i = from ; i <= to2 ; ++i) for (int i = from ; i <= to2 ; ++i)
v.push_back(vmime::create <IMAPMessage>(this, i)); v.push_back(vmime::create <IMAPMessage>(thisFolder, i));
return (v); return (v);
} }
@ -487,9 +498,10 @@ std::vector <ref <message> > IMAPFolder::getMessages(const std::vector <int>& nu
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <IMAPFolder> thisFolder = thisRef().dynamicCast <IMAPFolder>();
for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it) for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it)
v.push_back(vmime::create <IMAPMessage>(this, *it)); v.push_back(vmime::create <IMAPMessage>(thisFolder, *it));
return (v); return (v);
} }
@ -506,16 +518,20 @@ const int IMAPFolder::getMessageCount()
ref <folder> IMAPFolder::getFolder(const folder::path::component& name) ref <folder> IMAPFolder::getFolder(const folder::path::component& name)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
return vmime::create <IMAPFolder>(m_path / name, m_store); return vmime::create <IMAPFolder>(m_path / name, store);
} }
std::vector <ref <folder> > IMAPFolder::getFolders(const bool recursive) std::vector <ref <folder> > IMAPFolder::getFolders(const bool recursive)
{ {
if (!isOpen() && !m_store) ref <IMAPStore> store = m_store.acquire();
if (!isOpen() && !store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
// Eg. List folders in '/foo/bar' // Eg. List folders in '/foo/bar'
@ -591,7 +607,7 @@ std::vector <ref <folder> > IMAPFolder::getFolders(const bool recursive)
const class IMAPParser::mailbox_flag_list* mailbox_flag_list = const class IMAPParser::mailbox_flag_list* mailbox_flag_list =
mailboxData->mailbox_list()->mailbox_flag_list(); mailboxData->mailbox_list()->mailbox_flag_list();
v.push_back(vmime::create <IMAPFolder>(path, m_store, v.push_back(vmime::create <IMAPFolder>(path, store,
IMAPUtils::folderTypeFromFlags(mailbox_flag_list), IMAPUtils::folderTypeFromFlags(mailbox_flag_list),
IMAPUtils::folderFlagsFromFlags(mailbox_flag_list))); IMAPUtils::folderFlagsFromFlags(mailbox_flag_list)));
} }
@ -604,7 +620,9 @@ std::vector <ref <folder> > IMAPFolder::getFolders(const bool recursive)
void IMAPFolder::fetchMessages(std::vector <ref <message> >& msg, const int options, void IMAPFolder::fetchMessages(std::vector <ref <message> >& msg, const int options,
utility::progressListener* progress) utility::progressListener* progress)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -691,12 +709,14 @@ void IMAPFolder::fetchMessages(std::vector <ref <message> >& msg, const int opti
void IMAPFolder::fetchMessage(ref <message> msg, const int options) void IMAPFolder::fetchMessage(ref <message> msg, const int options)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
msg.dynamicCast <IMAPMessage>()->fetch(this, options); msg.dynamicCast <IMAPMessage>()->fetch(thisRef().dynamicCast <IMAPFolder>(), options);
} }
@ -713,19 +733,19 @@ ref <folder> IMAPFolder::getParent()
if (m_path.isEmpty()) if (m_path.isEmpty())
return NULL; return NULL;
else else
return vmime::create <IMAPFolder>(m_path.getParent(), m_store); return vmime::create <IMAPFolder>(m_path.getParent(), m_store.acquire());
} }
weak_ref <const store> IMAPFolder::getStore() const ref <const store> IMAPFolder::getStore() const
{ {
return (m_store); return m_store.acquire();
} }
weak_ref <store> IMAPFolder::getStore() ref <store> IMAPFolder::getStore()
{ {
return (m_store); return m_store.acquire();
} }
@ -753,7 +773,9 @@ void IMAPFolder::onStoreDisconnected()
void IMAPFolder::deleteMessage(const int num) void IMAPFolder::deleteMessage(const int num)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -802,10 +824,12 @@ void IMAPFolder::deleteMessage(const int num)
void IMAPFolder::deleteMessages(const int from, const int to) void IMAPFolder::deleteMessages(const int from, const int to)
{ {
ref <IMAPStore> store = m_store.acquire();
if (from < 1 || (to < from && to != -1)) if (from < 1 || (to < from && to != -1))
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -865,10 +889,12 @@ void IMAPFolder::deleteMessages(const int from, const int to)
void IMAPFolder::deleteMessages(const std::vector <int>& nums) void IMAPFolder::deleteMessages(const std::vector <int>& nums)
{ {
ref <IMAPStore> store = m_store.acquire();
if (nums.empty()) if (nums.empty())
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -924,10 +950,12 @@ void IMAPFolder::deleteMessages(const std::vector <int>& nums)
void IMAPFolder::setMessageFlags(const int from, const int to, const int flags, const int mode) void IMAPFolder::setMessageFlags(const int from, const int to, const int flags, const int mode)
{ {
ref <IMAPStore> store = m_store.acquire();
if (from < 1 || (to < from && to != -1)) if (from < 1 || (to < from && to != -1))
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1012,7 +1040,9 @@ void IMAPFolder::setMessageFlags(const int from, const int to, const int flags,
void IMAPFolder::setMessageFlags(const std::vector <int>& nums, const int flags, const int mode) void IMAPFolder::setMessageFlags(const std::vector <int>& nums, const int flags, const int mode)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1142,7 +1172,9 @@ void IMAPFolder::addMessage(ref <vmime::message> msg, const int flags,
void IMAPFolder::addMessage(utility::inputStream& is, const int size, const int flags, void IMAPFolder::addMessage(utility::inputStream& is, const int size, const int flags,
vmime::datetime* date, utility::progressListener* progress) vmime::datetime* date, utility::progressListener* progress)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1243,8 +1275,8 @@ void IMAPFolder::addMessage(utility::inputStream& is, const int size, const int
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {
@ -1261,7 +1293,9 @@ void IMAPFolder::addMessage(utility::inputStream& is, const int size, const int
void IMAPFolder::expunge() void IMAPFolder::expunge()
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1330,8 +1364,8 @@ void IMAPFolder::expunge()
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {
@ -1349,13 +1383,15 @@ void IMAPFolder::expunge()
void IMAPFolder::rename(const folder::path& newPath) void IMAPFolder::rename(const folder::path& newPath)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (m_path.isEmpty() || newPath.isEmpty()) else if (m_path.isEmpty() || newPath.isEmpty())
throw exceptions::illegal_operation("Cannot rename root folder"); throw exceptions::illegal_operation("Cannot rename root folder");
else if (m_path.getSize() == 1 && m_name.getBuffer() == "INBOX") else if (m_path.getSize() == 1 && m_name.getBuffer() == "INBOX")
throw exceptions::illegal_operation("Cannot rename 'INBOX' folder"); throw exceptions::illegal_operation("Cannot rename 'INBOX' folder");
else if (!m_store->isValidFolderName(newPath.getLastComponent())) else if (!store->isValidFolderName(newPath.getLastComponent()))
throw exceptions::invalid_folder_name(); throw exceptions::invalid_folder_name();
// Build the request text // Build the request text
@ -1392,8 +1428,8 @@ void IMAPFolder::rename(const folder::path& newPath)
notifyFolder(event); notifyFolder(event);
// Notify folders with the same path and sub-folders // Notify folders with the same path and sub-folders
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == oldPath) if ((*it) != this && (*it)->getFullPath() == oldPath)
{ {
@ -1424,7 +1460,9 @@ void IMAPFolder::rename(const folder::path& newPath)
void IMAPFolder::copyMessage(const folder::path& dest, const int num) void IMAPFolder::copyMessage(const folder::path& dest, const int num)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1440,8 +1478,8 @@ void IMAPFolder::copyMessage(const folder::path& dest, const int num)
std::vector <int> nums; std::vector <int> nums;
nums.push_back(num); nums.push_back(num);
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it)->getFullPath() == dest) if ((*it)->getFullPath() == dest)
{ {
@ -1458,7 +1496,9 @@ void IMAPFolder::copyMessage(const folder::path& dest, const int num)
void IMAPFolder::copyMessages(const folder::path& dest, const int from, const int to) void IMAPFolder::copyMessages(const folder::path& dest, const int from, const int to)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1486,8 +1526,8 @@ void IMAPFolder::copyMessages(const folder::path& dest, const int from, const in
for (int i = from, j = 0 ; i <= to2 ; ++i, ++j) for (int i = from, j = 0 ; i <= to2 ; ++i, ++j)
nums[j] = i; nums[j] = i;
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it)->getFullPath() == dest) if ((*it)->getFullPath() == dest)
{ {
@ -1504,7 +1544,9 @@ void IMAPFolder::copyMessages(const folder::path& dest, const int from, const in
void IMAPFolder::copyMessages(const folder::path& dest, const std::vector <int>& nums) void IMAPFolder::copyMessages(const folder::path& dest, const std::vector <int>& nums)
{ {
if (!m_store) ref <IMAPStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1515,8 +1557,8 @@ void IMAPFolder::copyMessages(const folder::path& dest, const std::vector <int>&
// Notify message count changed // Notify message count changed
const int count = nums.size(); const int count = nums.size();
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it)->getFullPath() == dest) if ((*it)->getFullPath() == dest)
{ {
@ -1556,6 +1598,8 @@ void IMAPFolder::copyMessages(const string& set, const folder::path& dest)
void IMAPFolder::status(int& count, int& unseen) void IMAPFolder::status(int& count, int& unseen)
{ {
ref <IMAPStore> store = m_store.acquire();
count = 0; count = 0;
unseen = 0; unseen = 0;
@ -1567,16 +1611,16 @@ void IMAPFolder::status(int& count, int& unseen)
command << " (MESSAGES UNSEEN)"; command << " (MESSAGES UNSEEN)";
// Send the request // Send the request
m_store->m_connection->send(true, command.str(), true); m_connection->send(true, command.str(), true);
// Get the response // Get the response
utility::auto_ptr <IMAPParser::response> resp(m_store->m_connection->readResponse()); utility::auto_ptr <IMAPParser::response> resp(m_connection->readResponse());
if (resp->isBad() || resp->response_done()->response_tagged()-> if (resp->isBad() || resp->response_done()->response_tagged()->
resp_cond_state()->status() != IMAPParser::resp_cond_state::OK) resp_cond_state()->status() != IMAPParser::resp_cond_state::OK)
{ {
throw exceptions::command_error("STATUS", throw exceptions::command_error("STATUS",
m_store->m_connection->getParser()->lastLine(), "bad response"); m_connection->getParser()->lastLine(), "bad response");
} }
const std::vector <IMAPParser::continue_req_or_response_data*>& respDataList = const std::vector <IMAPParser::continue_req_or_response_data*>& respDataList =
@ -1588,7 +1632,7 @@ void IMAPFolder::status(int& count, int& unseen)
if ((*it)->response_data() == NULL) if ((*it)->response_data() == NULL)
{ {
throw exceptions::command_error("STATUS", throw exceptions::command_error("STATUS",
m_store->m_connection->getParser()->lastLine(), "invalid response"); m_connection->getParser()->lastLine(), "invalid response");
} }
const IMAPParser::response_data* responseData = (*it)->response_data(); const IMAPParser::response_data* responseData = (*it)->response_data();
@ -1644,8 +1688,8 @@ void IMAPFolder::status(int& count, int& unseen)
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <IMAPFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {

View File

@ -53,7 +53,7 @@ public:
ref <const structure> getStructure() const; ref <const structure> getStructure() const;
ref <structure> getStructure(); ref <structure> getStructure();
weak_ref <const IMAPpart> getParent() const { return (m_parent); } ref <const IMAPpart> getParent() const { return m_parent.acquire(); }
const mediaType& getType() const { return (m_mediaType); } const mediaType& getType() const { return (m_mediaType); }
const int getSize() const { return (m_size); } const int getSize() const { return (m_size); }
@ -272,18 +272,20 @@ private:
// //
IMAPMessage::IMAPMessage(IMAPFolder* folder, const int num) IMAPMessage::IMAPMessage(ref <IMAPFolder> folder, const int num)
: m_folder(folder), m_num(num), m_size(-1), m_flags(FLAG_UNDEFINED), : m_folder(folder), m_num(num), m_size(-1), m_flags(FLAG_UNDEFINED),
m_expunged(false), m_structure(NULL) m_expunged(false), m_structure(NULL)
{ {
m_folder->registerMessage(this); folder->registerMessage(this);
} }
IMAPMessage::~IMAPMessage() IMAPMessage::~IMAPMessage()
{ {
if (m_folder) ref <IMAPFolder> folder = m_folder.acquire();
m_folder->unregisterMessage(this);
if (folder)
folder->unregisterMessage(this);
} }
@ -359,7 +361,9 @@ ref <const header> IMAPMessage::getHeader() const
void IMAPMessage::extract(utility::outputStream& os, utility::progressListener* progress, void IMAPMessage::extract(utility::outputStream& os, utility::progressListener* progress,
const int start, const int length, const bool peek) const const int start, const int length, const bool peek) const
{ {
if (!m_folder) ref <const IMAPFolder> folder = m_folder.acquire();
if (!folder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
extract(NULL, os, progress, start, length, false, peek); extract(NULL, os, progress, start, length, false, peek);
@ -370,7 +374,9 @@ void IMAPMessage::extractPart
(ref <const part> p, utility::outputStream& os, utility::progressListener* progress, (ref <const part> p, utility::outputStream& os, utility::progressListener* progress,
const int start, const int length, const bool peek) const const int start, const int length, const bool peek) const
{ {
if (!m_folder) ref <const IMAPFolder> folder = m_folder.acquire();
if (!folder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
extract(p, os, progress, start, length, false, peek); extract(p, os, progress, start, length, false, peek);
@ -379,7 +385,9 @@ void IMAPMessage::extractPart
void IMAPMessage::fetchPartHeader(ref <part> p) void IMAPMessage::fetchPartHeader(ref <part> p)
{ {
if (!m_folder) ref <IMAPFolder> folder = m_folder.acquire();
if (!folder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
std::ostringstream oss; std::ostringstream oss;
@ -395,6 +403,8 @@ void IMAPMessage::extract(ref <const part> p, utility::outputStream& os,
utility::progressListener* progress, const int start, utility::progressListener* progress, const int start,
const int length, const bool headerOnly, const bool peek) const const int length, const bool headerOnly, const bool peek) const
{ {
ref <const IMAPFolder> folder = m_folder.acquire();
IMAPMessage_literalHandler literalHandler(os, progress); IMAPMessage_literalHandler literalHandler(os, progress);
// Construct section identifier // Construct section identifier
@ -402,7 +412,7 @@ void IMAPMessage::extract(ref <const part> p, utility::outputStream& os,
if (p != NULL) if (p != NULL)
{ {
weak_ref <const IMAPpart> currentPart = p.dynamicCast <const IMAPpart>(); ref <const IMAPpart> currentPart = p.dynamicCast <const IMAPpart>();
std::vector <int> numbers; std::vector <int> numbers;
numbers.push_back(currentPart->getNumber()); numbers.push_back(currentPart->getNumber());
@ -437,17 +447,17 @@ void IMAPMessage::extract(ref <const part> p, utility::outputStream& os,
command << "<" << start << "." << length << ">"; command << "<" << start << "." << length << ">";
// Send the request // Send the request
m_folder->m_connection->send(true, command.str(), true); folder.constCast <IMAPFolder>()->m_connection->send(true, command.str(), true);
// Get the response // Get the response
utility::auto_ptr <IMAPParser::response> resp utility::auto_ptr <IMAPParser::response> resp
(m_folder->m_connection->readResponse(&literalHandler)); (folder.constCast <IMAPFolder>()->m_connection->readResponse(&literalHandler));
if (resp->isBad() || resp->response_done()->response_tagged()-> if (resp->isBad() || resp->response_done()->response_tagged()->
resp_cond_state()->status() != IMAPParser::resp_cond_state::OK) resp_cond_state()->status() != IMAPParser::resp_cond_state::OK)
{ {
throw exceptions::command_error("FETCH", throw exceptions::command_error("FETCH",
m_folder->m_connection->getParser()->lastLine(), "bad response"); folder.constCast <IMAPFolder>()->m_connection->getParser()->lastLine(), "bad response");
} }
@ -458,9 +468,11 @@ void IMAPMessage::extract(ref <const part> p, utility::outputStream& os,
} }
void IMAPMessage::fetch(IMAPFolder* folder, const int options) void IMAPMessage::fetch(ref <IMAPFolder> msgFolder, const int options)
{ {
if (m_folder != folder) ref <IMAPFolder> folder = m_folder.acquire();
if (folder != msgFolder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
// Send the request // Send the request
@ -469,16 +481,16 @@ void IMAPMessage::fetch(IMAPFolder* folder, const int options)
const string command = IMAPUtils::buildFetchRequest(list, options); const string command = IMAPUtils::buildFetchRequest(list, options);
m_folder->m_connection->send(true, command, true); folder->m_connection->send(true, command, true);
// Get the response // Get the response
utility::auto_ptr <IMAPParser::response> resp(m_folder->m_connection->readResponse()); utility::auto_ptr <IMAPParser::response> resp(folder->m_connection->readResponse());
if (resp->isBad() || resp->response_done()->response_tagged()-> if (resp->isBad() || resp->response_done()->response_tagged()->
resp_cond_state()->status() != IMAPParser::resp_cond_state::OK) resp_cond_state()->status() != IMAPParser::resp_cond_state::OK)
{ {
throw exceptions::command_error("FETCH", throw exceptions::command_error("FETCH",
m_folder->m_connection->getParser()->lastLine(), "bad response"); folder->m_connection->getParser()->lastLine(), "bad response");
} }
const std::vector <IMAPParser::continue_req_or_response_data*>& respDataList = const std::vector <IMAPParser::continue_req_or_response_data*>& respDataList =
@ -490,7 +502,7 @@ void IMAPMessage::fetch(IMAPFolder* folder, const int options)
if ((*it)->response_data() == NULL) if ((*it)->response_data() == NULL)
{ {
throw exceptions::command_error("FETCH", throw exceptions::command_error("FETCH",
m_folder->m_connection->getParser()->lastLine(), "invalid response"); folder->m_connection->getParser()->lastLine(), "invalid response");
} }
const IMAPParser::message_data* messageData = const IMAPParser::message_data* messageData =
@ -512,6 +524,8 @@ void IMAPMessage::fetch(IMAPFolder* folder, const int options)
void IMAPMessage::processFetchResponse void IMAPMessage::processFetchResponse
(const int options, const IMAPParser::msg_att* msgAtt) (const int options, const IMAPParser::msg_att* msgAtt)
{ {
ref <IMAPFolder> folder = m_folder.acquire();
// Get message attributes // Get message attributes
const std::vector <IMAPParser::msg_att_item*> atts = const std::vector <IMAPParser::msg_att_item*> atts =
msgAtt->items(); msgAtt->items();
@ -531,7 +545,7 @@ void IMAPMessage::processFetchResponse
case IMAPParser::msg_att_item::UID: case IMAPParser::msg_att_item::UID:
{ {
std::ostringstream oss; std::ostringstream oss;
oss << m_folder->m_uidValidity << ":" << (*it)->unique_id()->value(); oss << folder->m_uidValidity << ":" << (*it)->unique_id()->value();
m_uid = oss.str(); m_uid = oss.str();
break; break;
@ -681,9 +695,11 @@ void IMAPMessage::convertAddressList
void IMAPMessage::setFlags(const int flags, const int mode) void IMAPMessage::setFlags(const int flags, const int mode)
{ {
if (!m_folder) ref <IMAPFolder> folder = m_folder.acquire();
if (!folder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
else if (m_folder->m_mode == folder::MODE_READ_ONLY) else if (folder->m_mode == folder::MODE_READ_ONLY)
throw exceptions::illegal_state("Folder is read-only"); throw exceptions::illegal_state("Folder is read-only");
// Build the request text // Build the request text
@ -723,16 +739,16 @@ void IMAPMessage::setFlags(const int flags, const int mode)
command << *(flagList.end() - 1) << ")"; command << *(flagList.end() - 1) << ")";
// Send the request // Send the request
m_folder->m_connection->send(true, command.str(), true); folder->m_connection->send(true, command.str(), true);
// Get the response // Get the response
utility::auto_ptr <IMAPParser::response> resp(m_folder->m_connection->readResponse()); utility::auto_ptr <IMAPParser::response> resp(folder->m_connection->readResponse());
if (resp->isBad() || resp->response_done()->response_tagged()-> if (resp->isBad() || resp->response_done()->response_tagged()->
resp_cond_state()->status() != IMAPParser::resp_cond_state::OK) resp_cond_state()->status() != IMAPParser::resp_cond_state::OK)
{ {
throw exceptions::command_error("STORE", throw exceptions::command_error("STORE",
m_folder->m_connection->getParser()->lastLine(), "bad response"); folder->m_connection->getParser()->lastLine(), "bad response");
} }
// Update the local flags for this message // Update the local flags for this message
@ -776,13 +792,12 @@ void IMAPMessage::setFlags(const int flags, const int mode)
nums.push_back(m_num); nums.push_back(m_num);
events::messageChangedEvent event events::messageChangedEvent event
(m_folder->thisRef().dynamicCast <folder>(), (folder, events::messageChangedEvent::TYPE_FLAGS, nums);
events::messageChangedEvent::TYPE_FLAGS, nums);
for (std::list <IMAPFolder*>::iterator it = m_folder->m_store->m_folders.begin() ; for (std::list <IMAPFolder*>::iterator it = folder->m_store.acquire()->m_folders.begin() ;
it != m_folder->m_store->m_folders.end() ; ++it) it != folder->m_store.acquire()->m_folders.end() ; ++it)
{ {
if ((*it)->getFullPath() == m_folder->m_path) if ((*it)->getFullPath() == folder->m_path)
(*it)->notifyMessageChanged(event); (*it)->notifyMessageChanged(event);
} }
} }

View File

@ -63,7 +63,8 @@ ref <folder> IMAPStore::getRootFolder()
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <IMAPFolder>(folder::path(), this); return vmime::create <IMAPFolder>(folder::path(),
thisRef().dynamicCast <IMAPStore>());
} }
@ -72,7 +73,8 @@ ref <folder> IMAPStore::getDefaultFolder()
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <IMAPFolder>(folder::path::component("INBOX"), this); return vmime::create <IMAPFolder>(folder::path::component("INBOX"),
thisRef().dynamicCast <IMAPStore>());
} }
@ -81,7 +83,7 @@ ref <folder> IMAPStore::getFolder(const folder::path& path)
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <IMAPFolder>(path, this); return vmime::create <IMAPFolder>(path, thisRef().dynamicCast <IMAPStore>());
} }
@ -97,7 +99,7 @@ void IMAPStore::connect()
throw exceptions::already_connected(); throw exceptions::already_connected();
m_connection = vmime::create <IMAPConnection> m_connection = vmime::create <IMAPConnection>
(thisWeakRef().dynamicCast <IMAPStore>(), getAuthenticator()); (thisRef().dynamicCast <IMAPStore>(), getAuthenticator());
try try
{ {

View File

@ -36,23 +36,25 @@ namespace net {
namespace maildir { namespace maildir {
maildirFolder::maildirFolder(const folder::path& path, weak_ref <maildirStore> store) maildirFolder::maildirFolder(const folder::path& path, ref <maildirStore> store)
: m_store(store), m_path(path), : m_store(store), m_path(path),
m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()), m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()),
m_mode(-1), m_open(false), m_unreadMessageCount(0), m_messageCount(0) m_mode(-1), m_open(false), m_unreadMessageCount(0), m_messageCount(0)
{ {
m_store->registerFolder(this); store->registerFolder(this);
} }
maildirFolder::~maildirFolder() maildirFolder::~maildirFolder()
{ {
if (m_store) ref <maildirStore> store = m_store.acquire();
if (store)
{ {
if (m_open) if (m_open)
close(false); close(false);
m_store->unregisterFolder(this); store->unregisterFolder(this);
} }
else if (m_open) else if (m_open)
{ {
@ -92,7 +94,7 @@ const int maildirFolder::getFlags()
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
ref <utility::file> rootDir = fsf->create ref <utility::file> rootDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_CONTAINER)); (maildirUtils::getFolderFSPath(m_store.acquire(), m_path, maildirUtils::FOLDER_PATH_CONTAINER));
ref <utility::fileIterator> it = rootDir->getFiles(); ref <utility::fileIterator> it = rootDir->getFiles();
@ -125,7 +127,9 @@ const folder::path maildirFolder::getFullPath() const
void maildirFolder::open(const int mode, bool /* failIfModeIsNotAvailable */) void maildirFolder::open(const int mode, bool /* failIfModeIsNotAvailable */)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (isOpen()) else if (isOpen())
throw exceptions::illegal_state("Folder is already open"); throw exceptions::illegal_state("Folder is already open");
@ -141,7 +145,9 @@ void maildirFolder::open(const int mode, bool /* failIfModeIsNotAvailable */)
void maildirFolder::close(const bool expunge) void maildirFolder::close(const bool expunge)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (!isOpen()) if (!isOpen())
@ -187,13 +193,15 @@ void maildirFolder::unregisterMessage(maildirMessage* msg)
void maildirFolder::create(const int /* type */) void maildirFolder::create(const int /* type */)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (isOpen()) else if (isOpen())
throw exceptions::illegal_state("Folder is open"); throw exceptions::illegal_state("Folder is open");
else if (exists()) else if (exists())
throw exceptions::illegal_state("Folder already exists"); throw exceptions::illegal_state("Folder already exists");
else if (!m_store->isValidFolderName(m_name)) else if (!store->isValidFolderName(m_name))
throw exceptions::invalid_folder_name(); throw exceptions::invalid_folder_name();
// Create directory on file system // Create directory on file system
@ -201,18 +209,18 @@ void maildirFolder::create(const int /* type */)
{ {
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
if (!fsf->isValidPath(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_ROOT))) if (!fsf->isValidPath(maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_ROOT)))
throw exceptions::invalid_folder_name(); throw exceptions::invalid_folder_name();
ref <utility::file> rootDir = fsf->create ref <utility::file> rootDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_ROOT)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_ROOT));
ref <utility::file> newDir = fsf->create ref <utility::file> newDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_NEW)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_NEW));
ref <utility::file> tmpDir = fsf->create ref <utility::file> tmpDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_TMP)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_TMP));
ref <utility::file> curDir = fsf->create ref <utility::file> curDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_CUR)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_CUR));
rootDir->createDirectory(true); rootDir->createDirectory(true);
@ -236,17 +244,19 @@ void maildirFolder::create(const int /* type */)
const bool maildirFolder::exists() const bool maildirFolder::exists()
{ {
ref <maildirStore> store = m_store.acquire();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
ref <utility::file> rootDir = fsf->create ref <utility::file> rootDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_ROOT)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_ROOT));
ref <utility::file> newDir = fsf->create ref <utility::file> newDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_NEW)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_NEW));
ref <utility::file> tmpDir = fsf->create ref <utility::file> tmpDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_TMP)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_TMP));
ref <utility::file> curDir = fsf->create ref <utility::file> curDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_CUR)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_CUR));
return (rootDir->exists() && rootDir->isDirectory() && return (rootDir->exists() && rootDir->isDirectory() &&
newDir->exists() && newDir->isDirectory() && newDir->exists() && newDir->isDirectory() &&
@ -263,6 +273,8 @@ const bool maildirFolder::isOpen() const
void maildirFolder::scanFolder() void maildirFolder::scanFolder()
{ {
ref <maildirStore> store = m_store.acquire();
try try
{ {
m_messageCount = 0; m_messageCount = 0;
@ -271,11 +283,11 @@ void maildirFolder::scanFolder()
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
utility::file::path newDirPath = maildirUtils::getFolderFSPath utility::file::path newDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_NEW); (store, m_path, maildirUtils::FOLDER_PATH_NEW);
ref <utility::file> newDir = fsf->create(newDirPath); ref <utility::file> newDir = fsf->create(newDirPath);
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (store, m_path, maildirUtils::FOLDER_PATH_CUR);
ref <utility::file> curDir = fsf->create(curDirPath); ref <utility::file> curDir = fsf->create(curDirPath);
// New received messages (new/) // New received messages (new/)
@ -407,7 +419,7 @@ ref <message> maildirFolder::getMessage(const int num)
throw exceptions::message_not_found(); throw exceptions::message_not_found();
return vmime::create <maildirMessage> return vmime::create <maildirMessage>
(thisWeakRef().dynamicCast <maildirFolder>(), num); (thisRef().dynamicCast <maildirFolder>(), num);
} }
@ -421,12 +433,10 @@ std::vector <ref <message> > maildirFolder::getMessages(const int from, const in
throw exceptions::message_not_found(); throw exceptions::message_not_found();
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <maildirFolder> thisFolder = thisRef().dynamicCast <maildirFolder>();
for (int i = from ; i <= to2 ; ++i) for (int i = from ; i <= to2 ; ++i)
{ v.push_back(vmime::create <maildirMessage>(thisFolder, i));
v.push_back(vmime::create <maildirMessage>
(thisWeakRef().dynamicCast <maildirFolder>(), i));
}
return (v); return (v);
} }
@ -438,12 +448,10 @@ std::vector <ref <message> > maildirFolder::getMessages(const std::vector <int>&
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <maildirFolder> thisFolder = thisRef().dynamicCast <maildirFolder>();
for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it) for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it)
{ v.push_back(vmime::create <maildirMessage>(thisFolder, *it));
v.push_back(vmime::create <maildirMessage>
(thisWeakRef().dynamicCast <maildirFolder>(), *it));
}
return (v); return (v);
} }
@ -457,16 +465,20 @@ const int maildirFolder::getMessageCount()
ref <folder> maildirFolder::getFolder(const folder::path::component& name) ref <folder> maildirFolder::getFolder(const folder::path::component& name)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
return vmime::create <maildirFolder>(m_path / name, m_store); return vmime::create <maildirFolder>(m_path / name, store);
} }
std::vector <ref <folder> > maildirFolder::getFolders(const bool recursive) std::vector <ref <folder> > maildirFolder::getFolders(const bool recursive)
{ {
if (!isOpen() && !m_store) ref <maildirStore> store = m_store.acquire();
if (!isOpen() && !store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
std::vector <ref <folder> > list; std::vector <ref <folder> > list;
@ -479,12 +491,14 @@ std::vector <ref <folder> > maildirFolder::getFolders(const bool recursive)
void maildirFolder::listFolders(std::vector <ref <folder> >& list, const bool recursive) void maildirFolder::listFolders(std::vector <ref <folder> >& list, const bool recursive)
{ {
ref <maildirStore> store = m_store.acquire();
try try
{ {
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
ref <utility::file> rootDir = fsf->create ref <utility::file> rootDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, (maildirUtils::getFolderFSPath(store, m_path,
m_path.isEmpty() ? maildirUtils::FOLDER_PATH_ROOT m_path.isEmpty() ? maildirUtils::FOLDER_PATH_ROOT
: maildirUtils::FOLDER_PATH_CONTAINER)); : maildirUtils::FOLDER_PATH_CONTAINER));
@ -502,7 +516,7 @@ void maildirFolder::listFolders(std::vector <ref <folder> >& list, const bool re
m_path / file->getFullPath().getLastComponent(); m_path / file->getFullPath().getLastComponent();
ref <maildirFolder> subFolder = ref <maildirFolder> subFolder =
vmime::create <maildirFolder>(subPath, m_store); vmime::create <maildirFolder>(subPath, store);
list.push_back(subFolder); list.push_back(subFolder);
@ -525,27 +539,29 @@ void maildirFolder::listFolders(std::vector <ref <folder> >& list, const bool re
void maildirFolder::rename(const folder::path& newPath) void maildirFolder::rename(const folder::path& newPath)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (m_path.isEmpty() || newPath.isEmpty()) else if (m_path.isEmpty() || newPath.isEmpty())
throw exceptions::illegal_operation("Cannot rename root folder"); throw exceptions::illegal_operation("Cannot rename root folder");
else if (!m_store->isValidFolderName(newPath.getLastComponent())) else if (!store->isValidFolderName(newPath.getLastComponent()))
throw exceptions::invalid_folder_name(); throw exceptions::invalid_folder_name();
// Rename the directory on the file system // Rename the directory on the file system
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
ref <utility::file> rootDir = fsf->create ref <utility::file> rootDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_ROOT)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_ROOT));
ref <utility::file> contDir = fsf->create ref <utility::file> contDir = fsf->create
(maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_CONTAINER)); (maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_CONTAINER));
try try
{ {
const utility::file::path newRootPath = const utility::file::path newRootPath =
maildirUtils::getFolderFSPath(m_store, newPath, maildirUtils::FOLDER_PATH_ROOT); maildirUtils::getFolderFSPath(store, newPath, maildirUtils::FOLDER_PATH_ROOT);
const utility::file::path newContPath = const utility::file::path newContPath =
maildirUtils::getFolderFSPath(m_store, newPath, maildirUtils::FOLDER_PATH_CONTAINER); maildirUtils::getFolderFSPath(store, newPath, maildirUtils::FOLDER_PATH_CONTAINER);
rootDir->rename(newRootPath); rootDir->rename(newRootPath);
@ -563,9 +579,9 @@ void maildirFolder::rename(const folder::path& newPath)
{ {
// Revert to old location // Revert to old location
const utility::file::path rootPath = const utility::file::path rootPath =
maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_ROOT); maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_ROOT);
const utility::file::path contPath = const utility::file::path contPath =
maildirUtils::getFolderFSPath(m_store, m_path, maildirUtils::FOLDER_PATH_CONTAINER); maildirUtils::getFolderFSPath(store, m_path, maildirUtils::FOLDER_PATH_CONTAINER);
try try
{ {
@ -593,8 +609,8 @@ void maildirFolder::rename(const folder::path& newPath)
notifyFolder(event); notifyFolder(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <maildirFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <maildirFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == oldPath) if ((*it) != this && (*it)->getFullPath() == oldPath)
{ {
@ -647,10 +663,12 @@ void maildirFolder::deleteMessages(const std::vector <int>& nums)
void maildirFolder::setMessageFlags void maildirFolder::setMessageFlags
(const int from, const int to, const int flags, const int mode) (const int from, const int to, const int flags, const int mode)
{ {
ref <maildirStore> store = m_store.acquire();
if (from < 1 || (to < from && to != -1)) if (from < 1 || (to < from && to != -1))
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -733,7 +751,9 @@ void maildirFolder::setMessageFlags
void maildirFolder::setMessageFlags void maildirFolder::setMessageFlags
(const std::vector <int>& nums, const int flags, const int mode) (const std::vector <int>& nums, const int flags, const int mode)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -814,10 +834,12 @@ void maildirFolder::setMessageFlags
void maildirFolder::setMessageFlagsImpl void maildirFolder::setMessageFlagsImpl
(const std::vector <int>& nums, const int flags, const int mode) (const std::vector <int>& nums, const int flags, const int mode)
{ {
ref <maildirStore> store = m_store.acquire();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (store, m_path, maildirUtils::FOLDER_PATH_CUR);
for (std::vector <int>::const_iterator it = for (std::vector <int>::const_iterator it =
nums.begin() ; it != nums.end() ; ++it) nums.begin() ; it != nums.end() ; ++it)
@ -877,7 +899,9 @@ void maildirFolder::addMessage(ref <vmime::message> msg, const int flags,
void maildirFolder::addMessage(utility::inputStream& is, const int size, void maildirFolder::addMessage(utility::inputStream& is, const int size,
const int flags, vmime::datetime* /* date */, utility::progressListener* progress) const int flags, vmime::datetime* /* date */, utility::progressListener* progress)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -887,9 +911,9 @@ void maildirFolder::addMessage(utility::inputStream& is, const int size,
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
utility::file::path tmpDirPath = maildirUtils::getFolderFSPath utility::file::path tmpDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_TMP); (store, m_path, maildirUtils::FOLDER_PATH_TMP);
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (store, m_path, maildirUtils::FOLDER_PATH_CUR);
const utility::file::path::component filename = const utility::file::path::component filename =
maildirUtils::buildFilename(maildirUtils::generateId(), maildirUtils::buildFilename(maildirUtils::generateId(),
@ -940,8 +964,8 @@ void maildirFolder::addMessage(utility::inputStream& is, const int size,
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <maildirFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <maildirFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {
@ -1048,7 +1072,9 @@ void maildirFolder::copyMessageImpl(const utility::file::path& tmpDirPath,
void maildirFolder::copyMessage(const folder::path& dest, const int num) void maildirFolder::copyMessage(const folder::path& dest, const int num)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1059,7 +1085,9 @@ void maildirFolder::copyMessage(const folder::path& dest, const int num)
void maildirFolder::copyMessages(const folder::path& dest, const int from, const int to) void maildirFolder::copyMessages(const folder::path& dest, const int from, const int to)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1083,7 +1111,9 @@ void maildirFolder::copyMessages(const folder::path& dest, const int from, const
void maildirFolder::copyMessages(const folder::path& dest, const std::vector <int>& nums) void maildirFolder::copyMessages(const folder::path& dest, const std::vector <int>& nums)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1095,15 +1125,17 @@ void maildirFolder::copyMessages(const folder::path& dest, const std::vector <in
void maildirFolder::copyMessagesImpl(const folder::path& dest, const std::vector <int>& nums) void maildirFolder::copyMessagesImpl(const folder::path& dest, const std::vector <int>& nums)
{ {
ref <maildirStore> store = m_store.acquire();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (store, m_path, maildirUtils::FOLDER_PATH_CUR);
utility::file::path destCurDirPath = maildirUtils::getFolderFSPath utility::file::path destCurDirPath = maildirUtils::getFolderFSPath
(m_store, dest, maildirUtils::FOLDER_PATH_CUR); (store, dest, maildirUtils::FOLDER_PATH_CUR);
utility::file::path destTmpDirPath = maildirUtils::getFolderFSPath utility::file::path destTmpDirPath = maildirUtils::getFolderFSPath
(m_store, dest, maildirUtils::FOLDER_PATH_TMP); (store, dest, maildirUtils::FOLDER_PATH_TMP);
// Create destination directories // Create destination directories
try try
@ -1159,8 +1191,10 @@ void maildirFolder::copyMessagesImpl(const folder::path& dest, const std::vector
void maildirFolder::notifyMessagesCopied(const folder::path& dest) void maildirFolder::notifyMessagesCopied(const folder::path& dest)
{ {
for (std::list <maildirFolder*>::iterator it = m_store->m_folders.begin() ; ref <maildirStore> store = m_store.acquire();
it != m_store->m_folders.end() ; ++it)
for (std::list <maildirFolder*>::iterator it = store->m_folders.begin() ;
it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == dest) if ((*it) != this && (*it)->getFullPath() == dest)
{ {
@ -1177,6 +1211,8 @@ void maildirFolder::notifyMessagesCopied(const folder::path& dest)
void maildirFolder::status(int& count, int& unseen) void maildirFolder::status(int& count, int& unseen)
{ {
ref <maildirStore> store = m_store.acquire();
const int oldCount = m_messageCount; const int oldCount = m_messageCount;
scanFolder(); scanFolder();
@ -1200,8 +1236,8 @@ void maildirFolder::status(int& count, int& unseen)
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <maildirFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <maildirFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {
@ -1224,7 +1260,9 @@ void maildirFolder::status(int& count, int& unseen)
void maildirFolder::expunge() void maildirFolder::expunge()
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1234,7 +1272,7 @@ void maildirFolder::expunge()
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (store, m_path, maildirUtils::FOLDER_PATH_CUR);
std::vector <int> nums; std::vector <int> nums;
int unreadCount = 0; int unreadCount = 0;
@ -1289,8 +1327,8 @@ void maildirFolder::expunge()
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <maildirFolder*>::iterator it = m_store->m_folders.begin() ; for (std::list <maildirFolder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {
@ -1315,26 +1353,28 @@ ref <folder> maildirFolder::getParent()
if (m_path.isEmpty()) if (m_path.isEmpty())
return NULL; return NULL;
else else
return vmime::create <maildirFolder>(m_path.getParent(), m_store); return vmime::create <maildirFolder>(m_path.getParent(), m_store.acquire());
} }
weak_ref <const store> maildirFolder::getStore() const ref <const store> maildirFolder::getStore() const
{ {
return (m_store); return m_store.acquire();
} }
weak_ref <store> maildirFolder::getStore() ref <store> maildirFolder::getStore()
{ {
return (m_store); return m_store.acquire();
} }
void maildirFolder::fetchMessages(std::vector <ref <message> >& msg, void maildirFolder::fetchMessages(std::vector <ref <message> >& msg,
const int options, utility::progressListener* progress) const int options, utility::progressListener* progress)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -1345,12 +1385,12 @@ void maildirFolder::fetchMessages(std::vector <ref <message> >& msg,
if (progress) if (progress)
progress->start(total); progress->start(total);
weak_ref <maildirFolder> _this = thisWeakRef().dynamicCast <maildirFolder>(); ref <maildirFolder> thisFolder = thisRef().dynamicCast <maildirFolder>();
for (std::vector <ref <message> >::iterator it = msg.begin() ; for (std::vector <ref <message> >::iterator it = msg.begin() ;
it != msg.end() ; ++it) it != msg.end() ; ++it)
{ {
(*it).dynamicCast <maildirMessage>()->fetch(_this, options); (*it).dynamicCast <maildirMessage>()->fetch(thisFolder, options);
if (progress) if (progress)
progress->progress(++current, total); progress->progress(++current, total);
@ -1363,13 +1403,15 @@ void maildirFolder::fetchMessages(std::vector <ref <message> >& msg,
void maildirFolder::fetchMessage(ref <message> msg, const int options) void maildirFolder::fetchMessage(ref <message> msg, const int options)
{ {
if (!m_store) ref <maildirStore> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
msg.dynamicCast <maildirMessage>()->fetch msg.dynamicCast <maildirMessage>()->fetch
(thisWeakRef().dynamicCast <maildirFolder>(), options); (thisRef().dynamicCast <maildirFolder>(), options);
} }
@ -1384,7 +1426,7 @@ const int maildirFolder::getFetchCapabilities() const
const utility::file::path maildirFolder::getMessageFSPath(const int number) const const utility::file::path maildirFolder::getMessageFSPath(const int number) const
{ {
utility::file::path curDirPath = maildirUtils::getFolderFSPath utility::file::path curDirPath = maildirUtils::getFolderFSPath
(m_store, m_path, maildirUtils::FOLDER_PATH_CUR); (m_store.acquire(), m_path, maildirUtils::FOLDER_PATH_CUR);
return (curDirPath / m_messageInfos[number - 1].path); return (curDirPath / m_messageInfos[number - 1].path);
} }

View File

@ -43,7 +43,7 @@ class maildirPart : public part
{ {
public: public:
maildirPart(weak_ref <maildirPart> parent, const int number, const bodyPart& part); maildirPart(ref <maildirPart> parent, const int number, const bodyPart& part);
~maildirPart(); ~maildirPart();
@ -111,7 +111,7 @@ public:
{ {
} }
maildirStructure(weak_ref <maildirPart> parent, const bodyPart& part) maildirStructure(ref <maildirPart> parent, const bodyPart& part)
{ {
vmime::ref <maildirPart> mpart = vmime::create <maildirPart>(parent, 0, part); vmime::ref <maildirPart> mpart = vmime::create <maildirPart>(parent, 0, part);
mpart->initStructure(part); mpart->initStructure(part);
@ -119,7 +119,7 @@ public:
m_parts.push_back(mpart); m_parts.push_back(mpart);
} }
maildirStructure(weak_ref <maildirPart> parent, const std::vector <ref <const vmime::bodyPart> >& list) maildirStructure(ref <maildirPart> parent, const std::vector <ref <const vmime::bodyPart> >& list)
{ {
for (unsigned int i = 0 ; i < list.size() ; ++i) for (unsigned int i = 0 ; i < list.size() ; ++i)
{ {
@ -164,7 +164,7 @@ ref <maildirStructure> maildirStructure::m_emptyStructure = vmime::create <maild
maildirPart::maildirPart(weak_ref <maildirPart> parent, const int number, const bodyPart& part) maildirPart::maildirPart(ref <maildirPart> parent, const int number, const bodyPart& part)
: m_parent(parent), m_header(NULL), m_number(number) : m_parent(parent), m_header(NULL), m_number(number)
{ {
m_headerParsedOffset = part.getHeader()->getParsedOffset(); m_headerParsedOffset = part.getHeader()->getParsedOffset();
@ -191,7 +191,7 @@ void maildirPart::initStructure(const bodyPart& part)
else else
{ {
m_structure = vmime::create <maildirStructure> m_structure = vmime::create <maildirStructure>
(thisWeakRef().dynamicCast <maildirPart>(), (thisRef().dynamicCast <maildirPart>(),
part.getBody()->getPartList()); part.getBody()->getPartList());
} }
} }
@ -220,18 +220,20 @@ ref <structure> maildirPart::getStructure()
// maildirMessage // maildirMessage
// //
maildirMessage::maildirMessage(weak_ref <maildirFolder> folder, const int num) maildirMessage::maildirMessage(ref <maildirFolder> folder, const int num)
: m_folder(folder), m_num(num), m_size(-1), m_flags(FLAG_UNDEFINED), : m_folder(folder), m_num(num), m_size(-1), m_flags(FLAG_UNDEFINED),
m_expunged(false), m_structure(NULL) m_expunged(false), m_structure(NULL)
{ {
m_folder->registerMessage(this); folder->registerMessage(this);
} }
maildirMessage::~maildirMessage() maildirMessage::~maildirMessage()
{ {
if (m_folder) ref <maildirFolder> folder = m_folder.acquire();
m_folder->unregisterMessage(this);
if (folder)
folder->unregisterMessage(this);
} }
@ -306,10 +308,12 @@ const int maildirMessage::getFlags() const
void maildirMessage::setFlags(const int flags, const int mode) void maildirMessage::setFlags(const int flags, const int mode)
{ {
if (!m_folder) ref <maildirFolder> folder = m_folder.acquire();
if (!folder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
m_folder->setMessageFlags(m_num, m_num, flags, mode); folder->setMessageFlags(m_num, m_num, flags, mode);
} }
@ -336,9 +340,11 @@ void maildirMessage::extractImpl(utility::outputStream& os, utility::progressLis
const int start, const int length, const int partialStart, const int partialLength, const int start, const int length, const int partialStart, const int partialLength,
const bool /* peek */) const const bool /* peek */) const
{ {
ref <const maildirFolder> folder = m_folder.acquire();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
const utility::file::path path = m_folder->getMessageFSPath(m_num); const utility::file::path path = folder->getMessageFSPath(m_num);
ref <utility::file> file = fsf->create(path); ref <utility::file> file = fsf->create(path);
ref <utility::fileReader> reader = file->getFileReader(); ref <utility::fileReader> reader = file->getFileReader();
@ -379,11 +385,13 @@ void maildirMessage::extractImpl(utility::outputStream& os, utility::progressLis
void maildirMessage::fetchPartHeader(ref <part> p) void maildirMessage::fetchPartHeader(ref <part> p)
{ {
ref <maildirFolder> folder = m_folder.acquire();
ref <maildirPart> mp = p.dynamicCast <maildirPart>(); ref <maildirPart> mp = p.dynamicCast <maildirPart>();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();
const utility::file::path path = m_folder->getMessageFSPath(m_num); const utility::file::path path = folder->getMessageFSPath(m_num);
ref <utility::file> file = fsf->create(path); ref <utility::file> file = fsf->create(path);
ref <utility::fileReader> reader = file->getFileReader(); ref <utility::fileReader> reader = file->getFileReader();
@ -411,9 +419,11 @@ void maildirMessage::fetchPartHeader(ref <part> p)
} }
void maildirMessage::fetch(weak_ref <maildirFolder> folder, const int options) void maildirMessage::fetch(ref <maildirFolder> msgFolder, const int options)
{ {
if (m_folder != folder) ref <maildirFolder> folder = m_folder.acquire();
if (folder != msgFolder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory(); utility::fileSystemFactory* fsf = platformDependant::getHandler()->getFileSystemFactory();

View File

@ -75,7 +75,7 @@ ref <folder> maildirStore::getRootFolder()
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <maildirFolder>(folder::path(), return vmime::create <maildirFolder>(folder::path(),
thisWeakRef().dynamicCast <maildirStore>()); thisRef().dynamicCast <maildirStore>());
} }
@ -85,7 +85,7 @@ ref <folder> maildirStore::getDefaultFolder()
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <maildirFolder>(folder::path::component("inbox"), return vmime::create <maildirFolder>(folder::path::component("inbox"),
thisWeakRef().dynamicCast <maildirStore>()); thisRef().dynamicCast <maildirStore>());
} }
@ -95,7 +95,7 @@ ref <folder> maildirStore::getFolder(const folder::path& path)
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <maildirFolder>(path, return vmime::create <maildirFolder>(path,
thisWeakRef().dynamicCast <maildirStore>()); thisRef().dynamicCast <maildirStore>());
} }

View File

@ -34,7 +34,8 @@ const vmime::word maildirUtils::NEW_DIR("new", vmime::charset(vmime::charsets::U
const utility::file::path maildirUtils::getFolderFSPath const utility::file::path maildirUtils::getFolderFSPath
(weak_ref <maildirStore> store, const utility::path& folderPath, const FolderFSPathMode mode) (ref <const maildirStore> store, const utility::path& folderPath,
const FolderFSPathMode mode)
{ {
// Root path // Root path
utility::file::path path(store->getFileSystemPath()); utility::file::path path(store->getFileSystemPath());

View File

@ -30,23 +30,25 @@ namespace net {
namespace pop3 { namespace pop3 {
POP3Folder::POP3Folder(const folder::path& path, POP3Store* store) POP3Folder::POP3Folder(const folder::path& path, ref <POP3Store> store)
: m_store(store), m_path(path), : m_store(store), m_path(path),
m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()), m_name(path.isEmpty() ? folder::path::component("") : path.getLastComponent()),
m_mode(-1), m_open(false) m_mode(-1), m_open(false)
{ {
m_store->registerFolder(this); store->registerFolder(this);
} }
POP3Folder::~POP3Folder() POP3Folder::~POP3Folder()
{ {
if (m_store) ref <POP3Store> store = m_store.acquire();
if (store)
{ {
if (m_open) if (m_open)
close(false); close(false);
m_store->unregisterFolder(this); store->unregisterFolder(this);
} }
else if (m_open) else if (m_open)
{ {
@ -98,7 +100,9 @@ const folder::path POP3Folder::getFullPath() const
void POP3Folder::open(const int mode, bool failIfModeIsNotAvailable) void POP3Folder::open(const int mode, bool failIfModeIsNotAvailable)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (m_path.isEmpty()) if (m_path.isEmpty())
@ -113,15 +117,15 @@ void POP3Folder::open(const int mode, bool failIfModeIsNotAvailable)
} }
else if (m_path.getSize() == 1 && m_path[0].getBuffer() == "INBOX") else if (m_path.getSize() == 1 && m_path[0].getBuffer() == "INBOX")
{ {
m_store->sendRequest("STAT"); store->sendRequest("STAT");
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
if (!m_store->isSuccessResponse(response)) if (!store->isSuccessResponse(response))
throw exceptions::command_error("STAT", response); throw exceptions::command_error("STAT", response);
m_store->stripResponseCode(response, response); store->stripResponseCode(response, response);
std::istringstream iss(response); std::istringstream iss(response);
iss >> m_messageCount; iss >> m_messageCount;
@ -140,7 +144,9 @@ void POP3Folder::open(const int mode, bool failIfModeIsNotAvailable)
void POP3Folder::close(const bool expunge) void POP3Folder::close(const bool expunge)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (!isOpen()) if (!isOpen())
@ -148,10 +154,10 @@ void POP3Folder::close(const bool expunge)
if (!expunge) if (!expunge)
{ {
m_store->sendRequest("RSET"); store->sendRequest("RSET");
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
} }
m_open = false; m_open = false;
@ -178,7 +184,9 @@ void POP3Folder::create(const int /* type */)
const bool POP3Folder::exists() const bool POP3Folder::exists()
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
return (m_path.isEmpty() || (m_path.getSize() == 1 && m_path[0].getBuffer() == "INBOX")); return (m_path.isEmpty() || (m_path.getSize() == 1 && m_path[0].getBuffer() == "INBOX"));
@ -193,22 +201,26 @@ const bool POP3Folder::isOpen() const
ref <message> POP3Folder::getMessage(const int num) ref <message> POP3Folder::getMessage(const int num)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
else if (num < 1 || num > m_messageCount) else if (num < 1 || num > m_messageCount)
throw exceptions::message_not_found(); throw exceptions::message_not_found();
return vmime::create <POP3Message>(this, num); return vmime::create <POP3Message>(thisRef().dynamicCast <POP3Folder>(), num);
} }
std::vector <ref <message> > POP3Folder::getMessages(const int from, const int to) std::vector <ref <message> > POP3Folder::getMessages(const int from, const int to)
{ {
ref <POP3Store> store = m_store.acquire();
const int to2 = (to == -1 ? m_messageCount : to); const int to2 = (to == -1 ? m_messageCount : to);
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -216,9 +228,10 @@ std::vector <ref <message> > POP3Folder::getMessages(const int from, const int t
throw exceptions::message_not_found(); throw exceptions::message_not_found();
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <POP3Folder> thisFolder = thisRef().dynamicCast <POP3Folder>();
for (int i = from ; i <= to2 ; ++i) for (int i = from ; i <= to2 ; ++i)
v.push_back(vmime::create <POP3Message>(this, i)); v.push_back(vmime::create <POP3Message>(thisFolder, i));
return (v); return (v);
} }
@ -226,19 +239,22 @@ std::vector <ref <message> > POP3Folder::getMessages(const int from, const int t
std::vector <ref <message> > POP3Folder::getMessages(const std::vector <int>& nums) std::vector <ref <message> > POP3Folder::getMessages(const std::vector <int>& nums)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
std::vector <ref <message> > v; std::vector <ref <message> > v;
ref <POP3Folder> thisFolder = thisRef().dynamicCast <POP3Folder>();
for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it) for (std::vector <int>::const_iterator it = nums.begin() ; it != nums.end() ; ++it)
{ {
if (*it < 1|| *it > m_messageCount) if (*it < 1|| *it > m_messageCount)
throw exceptions::message_not_found(); throw exceptions::message_not_found();
v.push_back(vmime::create <POP3Message>(this, *it)); v.push_back(vmime::create <POP3Message>(thisFolder, *it));
} }
return (v); return (v);
@ -247,7 +263,9 @@ std::vector <ref <message> > POP3Folder::getMessages(const std::vector <int>& nu
const int POP3Folder::getMessageCount() const int POP3Folder::getMessageCount()
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -258,22 +276,26 @@ const int POP3Folder::getMessageCount()
ref <folder> POP3Folder::getFolder(const folder::path::component& name) ref <folder> POP3Folder::getFolder(const folder::path::component& name)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
return vmime::create <POP3Folder>(m_path / name, m_store); return vmime::create <POP3Folder>(m_path / name, store);
} }
std::vector <ref <folder> > POP3Folder::getFolders(const bool /* recursive */) std::vector <ref <folder> > POP3Folder::getFolders(const bool /* recursive */)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (m_path.isEmpty()) if (m_path.isEmpty())
{ {
std::vector <ref <folder> > v; std::vector <ref <folder> > v;
v.push_back(vmime::create <POP3Folder>(folder::path::component("INBOX"), m_store)); v.push_back(vmime::create <POP3Folder>(folder::path::component("INBOX"), store));
return (v); return (v);
} }
else else
@ -287,7 +309,9 @@ std::vector <ref <folder> > POP3Folder::getFolders(const bool /* recursive */)
void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int options, void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int options,
utility::progressListener* progress) utility::progressListener* progress)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -301,7 +325,8 @@ void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int opti
for (std::vector <ref <message> >::iterator it = msg.begin() ; for (std::vector <ref <message> >::iterator it = msg.begin() ;
it != msg.end() ; ++it) it != msg.end() ; ++it)
{ {
(*it).dynamicCast <POP3Message>()->fetch(this, options); (*it).dynamicCast <POP3Message>()->fetch
(thisRef().dynamicCast <POP3Folder>(), options);
if (progress) if (progress)
progress->progress(++current, total); progress->progress(++current, total);
@ -313,15 +338,15 @@ void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int opti
std::ostringstream command; std::ostringstream command;
command << "LIST"; command << "LIST";
m_store->sendRequest(command.str()); store->sendRequest(command.str());
// Get the response // Get the response
string response; string response;
m_store->readResponse(response, true, NULL); store->readResponse(response, true, NULL);
if (m_store->isSuccessResponse(response)) if (store->isSuccessResponse(response))
{ {
m_store->stripFirstLine(response, response, NULL); store->stripFirstLine(response, response, NULL);
// C: LIST // C: LIST
// S: +OK // S: +OK
@ -358,15 +383,15 @@ void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int opti
std::ostringstream command; std::ostringstream command;
command << "UIDL"; command << "UIDL";
m_store->sendRequest(command.str()); store->sendRequest(command.str());
// Get the response // Get the response
string response; string response;
m_store->readResponse(response, true, NULL); store->readResponse(response, true, NULL);
if (m_store->isSuccessResponse(response)) if (store->isSuccessResponse(response))
{ {
m_store->stripFirstLine(response, response, NULL); store->stripFirstLine(response, response, NULL);
// C: UIDL // C: UIDL
// S: +OK // S: +OK
@ -396,12 +421,15 @@ void POP3Folder::fetchMessages(std::vector <ref <message> >& msg, const int opti
void POP3Folder::fetchMessage(ref <message> msg, const int options) void POP3Folder::fetchMessage(ref <message> msg, const int options)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
msg.dynamicCast <POP3Message>()->fetch(this, options); msg.dynamicCast <POP3Message>()->fetch
(thisRef().dynamicCast <POP3Folder>(), options);
if (options & FETCH_SIZE) if (options & FETCH_SIZE)
{ {
@ -409,15 +437,15 @@ void POP3Folder::fetchMessage(ref <message> msg, const int options)
std::ostringstream command; std::ostringstream command;
command << "LIST " << msg->getNumber(); command << "LIST " << msg->getNumber();
m_store->sendRequest(command.str()); store->sendRequest(command.str());
// Get the response // Get the response
string response; string response;
m_store->readResponse(response, false, NULL); store->readResponse(response, false, NULL);
if (m_store->isSuccessResponse(response)) if (store->isSuccessResponse(response))
{ {
m_store->stripResponseCode(response, response); store->stripResponseCode(response, response);
// C: LIST 2 // C: LIST 2
// S: +OK 2 4242 // S: +OK 2 4242
@ -445,15 +473,15 @@ void POP3Folder::fetchMessage(ref <message> msg, const int options)
std::ostringstream command; std::ostringstream command;
command << "UIDL " << msg->getNumber(); command << "UIDL " << msg->getNumber();
m_store->sendRequest(command.str()); store->sendRequest(command.str());
// Get the response // Get the response
string response; string response;
m_store->readResponse(response, false, NULL); store->readResponse(response, false, NULL);
if (m_store->isSuccessResponse(response)) if (store->isSuccessResponse(response))
{ {
m_store->stripResponseCode(response, response); store->stripResponseCode(response, response);
// C: UIDL 2 // C: UIDL 2
// S: +OK 2 QhdPYR:00WBw1Ph7x7 // S: +OK 2 QhdPYR:00WBw1Ph7x7
@ -486,19 +514,19 @@ ref <folder> POP3Folder::getParent()
if (m_path.isEmpty()) if (m_path.isEmpty())
return NULL; return NULL;
else else
return vmime::create <POP3Folder>(m_path.getParent(), m_store); return vmime::create <POP3Folder>(m_path.getParent(), m_store.acquire());
} }
weak_ref <const store> POP3Folder::getStore() const ref <const store> POP3Folder::getStore() const
{ {
return (m_store); return m_store.acquire();
} }
weak_ref <store> POP3Folder::getStore() ref <store> POP3Folder::getStore()
{ {
return (m_store); return m_store.acquire();
} }
@ -522,7 +550,9 @@ void POP3Folder::onStoreDisconnected()
void POP3Folder::deleteMessage(const int num) void POP3Folder::deleteMessage(const int num)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -530,12 +560,12 @@ void POP3Folder::deleteMessage(const int num)
std::ostringstream command; std::ostringstream command;
command << "DELE " << num; command << "DELE " << num;
m_store->sendRequest(command.str()); store->sendRequest(command.str());
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
if (!m_store->isSuccessResponse(response)) if (!store->isSuccessResponse(response))
throw exceptions::command_error("DELE", response); throw exceptions::command_error("DELE", response);
// Update local flags // Update local flags
@ -562,10 +592,12 @@ void POP3Folder::deleteMessage(const int num)
void POP3Folder::deleteMessages(const int from, const int to) void POP3Folder::deleteMessages(const int from, const int to)
{ {
ref <POP3Store> store = m_store.acquire();
if (from < 1 || (to < from && to != -1)) if (from < 1 || (to < from && to != -1))
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -577,12 +609,12 @@ void POP3Folder::deleteMessages(const int from, const int to)
std::ostringstream command; std::ostringstream command;
command << "DELE " << i; command << "DELE " << i;
m_store->sendRequest(command.str()); store->sendRequest(command.str());
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
if (!m_store->isSuccessResponse(response)) if (!store->isSuccessResponse(response))
throw exceptions::command_error("DELE", response); throw exceptions::command_error("DELE", response);
} }
@ -612,10 +644,12 @@ void POP3Folder::deleteMessages(const int from, const int to)
void POP3Folder::deleteMessages(const std::vector <int>& nums) void POP3Folder::deleteMessages(const std::vector <int>& nums)
{ {
ref <POP3Store> store = m_store.acquire();
if (nums.empty()) if (nums.empty())
throw exceptions::invalid_argument(); throw exceptions::invalid_argument();
if (!m_store) if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
@ -626,12 +660,12 @@ void POP3Folder::deleteMessages(const std::vector <int>& nums)
std::ostringstream command; std::ostringstream command;
command << "DELE " << (*it); command << "DELE " << (*it);
m_store->sendRequest(command.str()); store->sendRequest(command.str());
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
if (!m_store->isSuccessResponse(response)) if (!store->isSuccessResponse(response))
throw exceptions::command_error("DELE", response); throw exceptions::command_error("DELE", response);
} }
@ -716,20 +750,22 @@ void POP3Folder::copyMessages(const folder::path& /* dest */, const std::vector
void POP3Folder::status(int& count, int& unseen) void POP3Folder::status(int& count, int& unseen)
{ {
if (!m_store) ref <POP3Store> store = m_store.acquire();
if (!store)
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
else if (!isOpen()) else if (!isOpen())
throw exceptions::illegal_state("Folder not open"); throw exceptions::illegal_state("Folder not open");
m_store->sendRequest("STAT"); store->sendRequest("STAT");
string response; string response;
m_store->readResponse(response, false); store->readResponse(response, false);
if (!m_store->isSuccessResponse(response)) if (!store->isSuccessResponse(response))
throw exceptions::command_error("STAT", response); throw exceptions::command_error("STAT", response);
m_store->stripResponseCode(response, response); store->stripResponseCode(response, response);
std::istringstream iss(response); std::istringstream iss(response);
iss >> count; iss >> count;
@ -759,8 +795,8 @@ void POP3Folder::status(int& count, int& unseen)
notifyMessageCount(event); notifyMessageCount(event);
// Notify folders with the same path // Notify folders with the same path
for (std::list <POP3Folder*>::iterator it = m_store->m_folders.begin() ; for (std::list <POP3Folder*>::iterator it = store->m_folders.begin() ;
it != m_store->m_folders.end() ; ++it) it != store->m_folders.end() ; ++it)
{ {
if ((*it) != this && (*it)->getFullPath() == m_path) if ((*it) != this && (*it)->getFullPath() == m_path)
{ {

View File

@ -29,17 +29,19 @@ namespace net {
namespace pop3 { namespace pop3 {
POP3Message::POP3Message(POP3Folder* folder, const int num) POP3Message::POP3Message(ref <POP3Folder> folder, const int num)
: m_folder(folder), m_num(num), m_size(-1), m_deleted(false) : m_folder(folder), m_num(num), m_size(-1), m_deleted(false)
{ {
m_folder->registerMessage(this); folder->registerMessage(this);
} }
POP3Message::~POP3Message() POP3Message::~POP3Message()
{ {
if (m_folder) ref <POP3Folder> folder = m_folder.acquire();
m_folder->unregisterMessage(this);
if (folder)
folder->unregisterMessage(this);
} }
@ -112,9 +114,11 @@ void POP3Message::extract(utility::outputStream& os,
utility::progressListener* progress, const int start, utility::progressListener* progress, const int start,
const int length, const bool /* peek */) const const int length, const bool /* peek */) const
{ {
if (!m_folder) ref <const POP3Folder> folder = m_folder.acquire();
if (!folder)
throw exceptions::illegal_state("Folder closed"); throw exceptions::illegal_state("Folder closed");
else if (!m_folder->m_store) else if (!folder->getStore())
throw exceptions::illegal_state("Store disconnected"); throw exceptions::illegal_state("Store disconnected");
if (start != 0 && length != -1) if (start != 0 && length != -1)
@ -124,17 +128,17 @@ void POP3Message::extract(utility::outputStream& os,
std::ostringstream oss; std::ostringstream oss;
oss << "RETR " << m_num; oss << "RETR " << m_num;
const_cast <POP3Folder*>(m_folder)->m_store->sendRequest(oss.str()); folder.constCast <POP3Folder>()->m_store.acquire()->sendRequest(oss.str());
try try
{ {
POP3Folder::MessageMap::const_iterator it = POP3Folder::MessageMap::const_iterator it =
m_folder->m_messages.find(const_cast <POP3Message*>(this)); folder->m_messages.find(const_cast <POP3Message*>(this));
const int totalSize = (it != m_folder->m_messages.end()) const int totalSize = (it != folder.constCast <POP3Folder>()->m_messages.end())
? (*it).second : 0; ? (*it).second : 0;
const_cast <POP3Folder*>(m_folder)->m_store-> folder.constCast <POP3Folder>()->m_store.acquire()->
readResponse(os, progress, totalSize); readResponse(os, progress, totalSize);
} }
catch (exceptions::command_error& e) catch (exceptions::command_error& e)
@ -160,9 +164,11 @@ void POP3Message::fetchPartHeader(ref <part> /* p */)
} }
void POP3Message::fetch(POP3Folder* folder, const int options) void POP3Message::fetch(ref <POP3Folder> msgFolder, const int options)
{ {
if (m_folder != folder) ref <POP3Folder> folder = m_folder.acquire();
if (folder != msgFolder)
throw exceptions::folder_not_found(); throw exceptions::folder_not_found();
// FETCH_STRUCTURE and FETCH_FLAGS are not supported by POP3. // FETCH_STRUCTURE and FETCH_FLAGS are not supported by POP3.
@ -185,12 +191,12 @@ void POP3Message::fetch(POP3Folder* folder, const int options)
std::ostringstream oss; std::ostringstream oss;
oss << "TOP " << m_num << " 0"; oss << "TOP " << m_num << " 0";
m_folder->m_store->sendRequest(oss.str()); folder->m_store.acquire()->sendRequest(oss.str());
try try
{ {
string buffer; string buffer;
m_folder->m_store->readResponse(buffer, true); folder->m_store.acquire()->readResponse(buffer, true);
m_header = vmime::create <header>(); m_header = vmime::create <header>();
m_header->parse(buffer); m_header->parse(buffer);

View File

@ -90,7 +90,8 @@ ref <folder> POP3Store::getDefaultFolder()
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <POP3Folder>(folder::path(folder::path::component("INBOX")), this); return vmime::create <POP3Folder>(folder::path(folder::path::component("INBOX")),
thisRef().dynamicCast <POP3Store>());
} }
@ -99,7 +100,8 @@ ref <folder> POP3Store::getRootFolder()
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <POP3Folder>(folder::path(), this); return vmime::create <POP3Folder>(folder::path(),
thisRef().dynamicCast <POP3Store>());
} }
@ -108,7 +110,8 @@ ref <folder> POP3Store::getFolder(const folder::path& path)
if (!isConnected()) if (!isConnected())
throw exceptions::illegal_state("Not connected"); throw exceptions::illegal_state("Not connected");
return vmime::create <POP3Folder>(path, this); return vmime::create <POP3Folder>(path,
thisRef().dynamicCast <POP3Store>());
} }

View File

@ -24,10 +24,6 @@
#include "vmime/types.hpp" #include "vmime/types.hpp"
#include "vmime/object.hpp" #include "vmime/object.hpp"
#include <algorithm> // std::find
#include <sstream> // std::ostringstream
#include <stdexcept> // std::runtime_error
#ifndef VMIME_BUILDING_DOC #ifndef VMIME_BUILDING_DOC
@ -37,155 +33,66 @@ namespace vmime
object::object() object::object()
: m_strongCount(0) : m_refMgr(new utility::refManager(this))
{ {
} }
object::object(const object&) object::object(const object&)
: m_strongCount(0) : m_refMgr(new utility::refManager(this))
{ {
// Not used }
object& object::operator=(const object&)
{
// Do _NOT_ copy 'm_refMgr'
return *this;
} }
object::~object() object::~object()
{ {
for (std::vector <utility::weak_ref_base*>::iterator delete m_refMgr;
it = m_weakRefs.begin() ; it != m_weakRefs.end() ; ++it) m_refMgr = 0;
{
(*it)->notifyObjectDestroyed();
}
#if VMIME_DEBUG
if (m_strongCount != 0)
{
std::ostringstream oss;
oss << "ERROR: Deleting object and strong count != 0."
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
}
void object::addStrong() const
{
++m_strongCount;
}
void object::addWeak(utility::weak_ref_base* w) const
{
m_weakRefs.push_back(w);
}
void object::releaseStrong() const
{
if (--m_strongCount == 0)
delete this;
}
void object::releaseWeak(utility::weak_ref_base* w) const
{
std::vector <utility::weak_ref_base*>::iterator
it = std::find(m_weakRefs.begin(), m_weakRefs.end(), w);
if (it != m_weakRefs.end())
m_weakRefs.erase(it);
#if VMIME_DEBUG
else
{
std::ostringstream oss;
oss << "ERROR: weak ref does not exist anymore!"
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
} }
ref <object> object::thisRef() ref <object> object::thisRef()
{ {
#if VMIME_DEBUG m_refMgr->addStrong();
if (m_strongCount == 0)
{
std::ostringstream oss;
oss << "ERROR: thisRef() MUST NOT be called from the object constructor."
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
return ref <object>::fromPtr(this); return ref <object>::fromPtr(this);
} }
ref <const object> object::thisRef() const ref <const object> object::thisRef() const
{ {
#if VMIME_DEBUG m_refMgr->addStrong();
if (m_strongCount == 0)
{
std::ostringstream oss;
oss << "ERROR: thisRef() MUST NOT be called from the object constructor."
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
return ref <const object>::fromPtr(this); return ref <const object>::fromPtr(this);
} }
weak_ref <object> object::thisWeakRef() weak_ref <object> object::thisWeakRef()
{ {
#if VMIME_DEBUG
if (m_strongCount == 0)
{
std::ostringstream oss;
oss << "ERROR: thisWeakRef() MUST NOT be called from the object constructor."
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
return weak_ref <object>(thisRef()); return weak_ref <object>(thisRef());
} }
weak_ref <const object> object::thisWeakRef() const weak_ref <const object> object::thisWeakRef() const
{ {
#if VMIME_DEBUG
if (m_strongCount == 0)
{
std::ostringstream oss;
oss << "ERROR: thisWeakRef() MUST NOT be called from the object constructor."
<< " (" << __FILE__ << ", line " << __LINE__ << ")" << std::endl;
throw std::runtime_error(oss.str());
}
#endif // VMIME_DEBUG
return weak_ref <const object>(thisRef()); return weak_ref <const object>(thisRef());
} }
const int object::getStrongRefCount() const void object::setRefManager(utility::refManager* mgr)
{ {
return m_strongCount; m_refMgr = mgr;
} }
const int object::getWeakRefCount() const utility::refManager* object::getRefManager() const
{ {
return static_cast <const int>(m_weakRefs.size()); return m_refMgr;
} }

View File

@ -28,7 +28,7 @@ namespace vmime
{ {
platformDependant::handler* platformDependant::sm_handler = NULL; ref <platformDependant::handler> platformDependant::sm_handler = NULL;
platformDependant::handler::~handler() platformDependant::handler::~handler()

View File

@ -44,8 +44,10 @@ defaultAuthenticator::~defaultAuthenticator()
const string defaultAuthenticator::getUsername() const const string defaultAuthenticator::getUsername() const
{ {
const string prefix = m_service->getInfos().getPropertyPrefix(); ref <const net::service> service = m_service.acquire();
const propertySet& props = m_service->getSession()->getProperties();
const string prefix = service->getInfos().getPropertyPrefix();
const propertySet& props = service->getSession()->getProperties();
if (props.hasProperty(prefix + net::serviceInfos::property::AUTH_USERNAME.getName())) if (props.hasProperty(prefix + net::serviceInfos::property::AUTH_USERNAME.getName()))
return props[prefix + net::serviceInfos::property::AUTH_USERNAME.getName()]; return props[prefix + net::serviceInfos::property::AUTH_USERNAME.getName()];
@ -56,8 +58,10 @@ const string defaultAuthenticator::getUsername() const
const string defaultAuthenticator::getPassword() const const string defaultAuthenticator::getPassword() const
{ {
const string prefix = m_service->getInfos().getPropertyPrefix(); ref <const net::service> service = m_service.acquire();
const propertySet& props = m_service->getSession()->getProperties();
const string prefix = service->getInfos().getPropertyPrefix();
const propertySet& props = service->getSession()->getProperties();
if (props.hasProperty(prefix + net::serviceInfos::property::AUTH_PASSWORD.getName())) if (props.hasProperty(prefix + net::serviceInfos::property::AUTH_PASSWORD.getName()))
return props[prefix + net::serviceInfos::property::AUTH_PASSWORD.getName()]; return props[prefix + net::serviceInfos::property::AUTH_PASSWORD.getName()];

166
src/utility/smartPtr.cpp Normal file
View File

@ -0,0 +1,166 @@
//
// VMime library (http://www.vmime.org)
// Copyright (C) 2002-2006 Vincent Richard <vincent@vincent-richard.net>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library. Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//
#include "vmime/object.hpp"
#include "vmime/utility/smartPtr.hpp"
namespace vmime {
namespace utility {
// refManager
refManager::refManager(object* obj)
: m_object(obj), m_strongCount(1), m_weakCount(1)
{
}
refManager::~refManager()
{
}
const bool refManager::addStrong()
{
if (m_strongCount <= 0)
return false;
m_strongCount.increment();
m_weakCount.increment();
return true;
}
void refManager::releaseStrong()
{
m_strongCount.decrement();
if (m_strongCount.compareExchange(0, -424242) == 0) // prevent from adding strong refs later
deleteObject();
releaseWeak();
}
void refManager::addWeak()
{
m_weakCount.increment();
}
void refManager::releaseWeak()
{
if (m_weakCount.decrement() == 0)
deleteManager();
}
object* refManager::getObject()
{
return m_object;
}
void refManager::deleteManager()
{
delete this;
}
void refManager::deleteObject()
{
try
{
m_object->setRefManager(0);
delete m_object;
}
catch (...)
{
// Exception in destructor
}
m_object = 0;
}
const long refManager::getStrongRefCount() const
{
return m_strongCount;
}
const long refManager::getWeakRefCount() const
{
return m_weakCount;
}
// refCounter
refCounter::refCounter(const long initialValue)
: m_value(initialValue)
{
}
refCounter::~refCounter()
{
}
const long refCounter::increment()
{
return ++m_value;
}
const long refCounter::decrement()
{
return --m_value;
}
const long refCounter::compareExchange(const long compare, const long exchangeWith)
{
const int prev = m_value;
if (m_value == compare)
m_value = exchangeWith;
return prev;
}
refCounter::operator long() const
{
return m_value;
}
} // utility
} // vmime

View File

@ -39,14 +39,13 @@ VMIME_TEST_SUITE_BEGIN
VMIME_TEST(testCast) VMIME_TEST(testCast)
VMIME_TEST(testContainer) VMIME_TEST(testContainer)
VMIME_TEST(testCompare) VMIME_TEST(testCompare)
VMIME_TEST(testThisRefCtor)
VMIME_TEST_LIST_END VMIME_TEST_LIST_END
struct A : public vmime::object struct A : public vmime::object
{ {
const int strongCount() const { return getStrongRefCount(); } const int strongCount() const { return getRefManager()->getStrongRefCount(); }
const int weakCount() const { return getWeakRefCount(); } const int weakCount() const { return getRefManager()->getWeakRefCount(); }
}; };
struct B : public virtual A { }; struct B : public virtual A { };
@ -65,12 +64,6 @@ VMIME_TEST_SUITE_BEGIN
bool* m_aliveFlag; bool* m_aliveFlag;
}; };
struct X : public vmime::object
{
X() { f(thisRef().dynamicCast <X>()); }
static void f(vmime::ref <X> /* x */) { }
};
void testNull() void testNull()
{ {
@ -94,13 +87,13 @@ VMIME_TEST_SUITE_BEGIN
VASSERT("1", r1.get() != 0); VASSERT("1", r1.get() != 0);
VASSERT("2", o1_alive); VASSERT("2", o1_alive);
VASSERT_EQ("3", 1, r1->strongCount()); VASSERT_EQ("3", 1, r1->strongCount());
VASSERT_EQ("4", 0, r1->weakCount()); VASSERT_EQ("4", 1, r1->weakCount());
vmime::ref <R> r2 = r1; vmime::ref <R> r2 = r1;
VASSERT("5", o1_alive); VASSERT("5", o1_alive);
VASSERT_EQ("6", 2, r1->strongCount()); VASSERT_EQ("6", 2, r1->strongCount());
VASSERT_EQ("7", 0, r1->weakCount()); VASSERT_EQ("7", 2, r1->weakCount());
bool o2_alive; bool o2_alive;
vmime::ref <R> r3 = vmime::create <R>(&o2_alive); vmime::ref <R> r3 = vmime::create <R>(&o2_alive);
@ -138,12 +131,12 @@ VMIME_TEST_SUITE_BEGIN
{ {
vmime::weak_ref <R> w1 = r3; vmime::weak_ref <R> w1 = r3;
VASSERT_EQ("22", 1, r3->weakCount()); VASSERT_EQ("22", 3, r3->weakCount());
} }
VASSERT("23", o2_alive); VASSERT("23", o2_alive);
VASSERT_EQ("24", 2, r3->strongCount()); VASSERT_EQ("24", 2, r3->strongCount());
VASSERT_EQ("25", 0, r3->weakCount()); VASSERT_EQ("25", 2, r3->weakCount());
} }
void testWeakRef() void testWeakRef()
@ -152,21 +145,21 @@ VMIME_TEST_SUITE_BEGIN
vmime::weak_ref <A> w1 = r1; vmime::weak_ref <A> w1 = r1;
VASSERT("1", r1.get() != 0); VASSERT("1", r1.get() != 0);
VASSERT("2", r1.get() == w1.get()); VASSERT("2", r1.get() == w1.acquire().get());
{ {
vmime::ref <A> r2 = r1; vmime::ref <A> r2 = r1;
VASSERT("3", r1.get() == r2.get()); VASSERT("3", r1.get() == r2.get());
VASSERT("4", r1.get() == w1.get()); VASSERT("4", r1.get() == w1.acquire().get());
} }
VASSERT("5", r1.get() != 0); VASSERT("5", r1.get() != 0);
VASSERT("6", r1.get() == w1.get()); VASSERT("6", r1.get() == w1.acquire().get());
r1 = 0; r1 = 0;
VASSERT("7", w1.get() == 0); VASSERT("7", w1.acquire().get() == 0);
} }
void testCast() void testCast()
@ -248,11 +241,5 @@ VMIME_TEST_SUITE_BEGIN
VASSERT("10", std::find(v.begin(), v.end(), r3) == v.end()); VASSERT("10", std::find(v.begin(), v.end(), r3) == v.end());
} }
void testThisRefCtor()
{
// BUGFIX: thisRef() MUST NOT be called from the object constructor
VASSERT_THROW("1", vmime::create <X>(), std::runtime_error);
}
VMIME_TEST_SUITE_END VMIME_TEST_SUITE_END

View File

@ -229,7 +229,7 @@ public:
private: private:
void setParentPart(weak_ref <bodyPart> parent); void setParentPart(ref <bodyPart> parent);
string m_prologText; string m_prologText;

View File

@ -75,7 +75,14 @@ public:
* *
* @return parent part or NULL if not known * @return parent part or NULL if not known
*/ */
weak_ref <bodyPart> getParentPart() const; ref <bodyPart> getParentPart();
/** Return the parent part of this part (const version).
*
* @return parent part or NULL if not known
*/
ref <const bodyPart> getParentPart() const;
ref <component> clone() const; ref <component> clone() const;
void copyFrom(const component& other); void copyFrom(const component& other);

View File

@ -306,13 +306,13 @@ public:
* *
* @return the store object to which this folder is attached * @return the store object to which this folder is attached
*/ */
virtual weak_ref <const store> getStore() const = 0; virtual ref <const store> getStore() const = 0;
/** Return a reference to the store to which this folder belongs. /** Return a reference to the store to which this folder belongs.
* *
* @return the store object to which this folder is attached * @return the store object to which this folder is attached
*/ */
virtual weak_ref <store> getStore() = 0; virtual ref <store> getStore() = 0;
/** Fetchable objects. /** Fetchable objects.
*/ */

View File

@ -50,7 +50,7 @@ class IMAPConnection : public object
{ {
public: public:
IMAPConnection(weak_ref <IMAPStore> store, ref <security::authenticator> auth); IMAPConnection(ref <IMAPStore> store, ref <security::authenticator> auth);
~IMAPConnection(); ~IMAPConnection();
@ -84,8 +84,8 @@ public:
ref <const IMAPTag> getTag() const; ref <const IMAPTag> getTag() const;
ref <const IMAPParser> getParser() const; ref <const IMAPParser> getParser() const;
weak_ref <const IMAPStore> getStore() const; ref <const IMAPStore> getStore() const;
weak_ref <IMAPStore> getStore(); ref <IMAPStore> getStore();
ref <session> getSession(); ref <session> getSession();

View File

@ -55,7 +55,7 @@ private:
friend class vmime::creator; // vmime::create <IMAPFolder> friend class vmime::creator; // vmime::create <IMAPFolder>
IMAPFolder(const folder::path& path, IMAPStore* store, const int type = TYPE_UNDEFINED, const int flags = FLAG_UNDEFINED); IMAPFolder(const folder::path& path, ref <IMAPStore> store, const int type = TYPE_UNDEFINED, const int flags = FLAG_UNDEFINED);
IMAPFolder(const IMAPFolder&) : folder() { } IMAPFolder(const IMAPFolder&) : folder() { }
~IMAPFolder(); ~IMAPFolder();
@ -109,8 +109,8 @@ public:
ref <folder> getParent(); ref <folder> getParent();
weak_ref <const store> getStore() const; ref <const store> getStore() const;
weak_ref <store> getStore(); ref <store> getStore();
void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL); void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL);
@ -134,7 +134,7 @@ private:
void copyMessages(const string& set, const folder::path& dest); void copyMessages(const string& set, const folder::path& dest);
IMAPStore* m_store; weak_ref <IMAPStore> m_store;
ref <IMAPConnection> m_connection; ref <IMAPConnection> m_connection;
folder::path m_path; folder::path m_path;

View File

@ -49,7 +49,7 @@ private:
friend class IMAPFolder; friend class IMAPFolder;
friend class vmime::creator; // vmime::create <IMAPMessage> friend class vmime::creator; // vmime::create <IMAPMessage>
IMAPMessage(IMAPFolder* folder, const int num); IMAPMessage(ref <IMAPFolder> folder, const int num);
IMAPMessage(const IMAPMessage&) : message() { } IMAPMessage(const IMAPMessage&) : message() { }
~IMAPMessage(); ~IMAPMessage();
@ -79,7 +79,7 @@ public:
private: private:
void fetch(IMAPFolder* folder, const int options); void fetch(ref <IMAPFolder> folder, const int options);
void processFetchResponse(const int options, const IMAPParser::msg_att* msgAtt); void processFetchResponse(const int options, const IMAPParser::msg_att* msgAtt);
@ -94,7 +94,7 @@ private:
void onFolderClosed(); void onFolderClosed();
IMAPFolder* m_folder; weak_ref <IMAPFolder> m_folder;
int m_num; int m_num;
int m_size; int m_size;

View File

@ -140,12 +140,12 @@ public:
} }
weak_ref <const IMAPTag> tag() const ref <const IMAPTag> getTag() const
{ {
return (m_tag); return m_tag.acquire();
} }
void setSocket(weak_ref <socket> sok) void setSocket(ref <socket> sok)
{ {
m_socket = sok; m_socket = sok;
} }
@ -474,7 +474,7 @@ public:
} }
} }
if (tagString == string(*(parser.tag()))) if (tagString == string(*parser.getTag()))
{ {
*currentPos = pos; *currentPos = pos;
} }
@ -5072,17 +5072,20 @@ public:
{ {
string receiveBuffer; string receiveBuffer;
ref <timeoutHandler> toh = m_timeoutHandler.acquire();
ref <socket> sok = m_socket.acquire();
while (receiveBuffer.empty()) while (receiveBuffer.empty())
{ {
// Check whether the time-out delay is elapsed // Check whether the time-out delay is elapsed
if (m_timeoutHandler && m_timeoutHandler->isTimeOut()) if (toh && toh->isTimeOut())
{ {
if (!m_timeoutHandler->handleTimeOut()) if (!toh->handleTimeOut())
throw exceptions::operation_timed_out(); throw exceptions::operation_timed_out();
} }
// We have received data: reset the time-out counter // We have received data: reset the time-out counter
m_socket->receive(receiveBuffer); sok->receive(receiveBuffer);
if (receiveBuffer.empty()) // buffer is empty if (receiveBuffer.empty()) // buffer is empty
{ {
@ -5091,8 +5094,8 @@ public:
} }
// We have received data ... // We have received data ...
if (m_timeoutHandler) if (toh)
m_timeoutHandler->resetTimeOut(); toh->resetTimeOut();
} }
m_buffer += receiveBuffer; m_buffer += receiveBuffer;
@ -5104,11 +5107,14 @@ public:
string::size_type len = 0; string::size_type len = 0;
string receiveBuffer; string receiveBuffer;
ref <timeoutHandler> toh = m_timeoutHandler.acquire();
ref <socket> sok = m_socket.acquire();
if (m_progress) if (m_progress)
m_progress->start(count); m_progress->start(count);
if (m_timeoutHandler) if (toh)
m_timeoutHandler->resetTimeOut(); toh->resetTimeOut();
if (!m_buffer.empty()) if (!m_buffer.empty())
{ {
@ -5129,16 +5135,16 @@ public:
while (len < count) while (len < count)
{ {
// Check whether the time-out delay is elapsed // Check whether the time-out delay is elapsed
if (m_timeoutHandler && m_timeoutHandler->isTimeOut()) if (toh && toh->isTimeOut())
{ {
if (!m_timeoutHandler->handleTimeOut()) if (!toh->handleTimeOut())
throw exceptions::operation_timed_out(); throw exceptions::operation_timed_out();
m_timeoutHandler->resetTimeOut(); toh->resetTimeOut();
} }
// Receive data from the socket // Receive data from the socket
m_socket->receive(receiveBuffer); sok->receive(receiveBuffer);
if (receiveBuffer.empty()) // buffer is empty if (receiveBuffer.empty()) // buffer is empty
{ {
@ -5147,8 +5153,8 @@ public:
} }
// We have received data: reset the time-out counter // We have received data: reset the time-out counter
if (m_timeoutHandler) if (toh)
m_timeoutHandler->resetTimeOut(); toh->resetTimeOut();
if (len + receiveBuffer.length() > count) if (len + receiveBuffer.length() > count)
{ {

View File

@ -56,7 +56,7 @@ private:
friend class vmime::creator; // vmime::create <maildirFolder> friend class vmime::creator; // vmime::create <maildirFolder>
maildirFolder(const folder::path& path, weak_ref <maildirStore> store); maildirFolder(const folder::path& path, ref <maildirStore> store);
maildirFolder(const maildirFolder&) : folder() { } maildirFolder(const maildirFolder&) : folder() { }
~maildirFolder(); ~maildirFolder();
@ -110,8 +110,8 @@ public:
ref <folder> getParent(); ref <folder> getParent();
weak_ref <const store> getStore() const; ref <const store> getStore() const;
weak_ref <store> getStore(); ref <store> getStore();
void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL); void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL);

View File

@ -47,7 +47,7 @@ class maildirMessage : public message
private: private:
maildirMessage(weak_ref <maildirFolder> folder, const int num); maildirMessage(ref <maildirFolder> folder, const int num);
maildirMessage(const maildirMessage&) : message() { } maildirMessage(const maildirMessage&) : message() { }
~maildirMessage(); ~maildirMessage();
@ -77,7 +77,7 @@ public:
private: private:
void fetch(weak_ref <maildirFolder> folder, const int options); void fetch(ref <maildirFolder> folder, const int options);
void onFolderClosed(); void onFolderClosed();

View File

@ -77,7 +77,7 @@ public:
* @param mode type of path to return (see FolderFSPathMode) * @param mode type of path to return (see FolderFSPathMode)
* @return filesystem path for the specified folder * @return filesystem path for the specified folder
*/ */
static const utility::file::path getFolderFSPath(weak_ref <maildirStore> store, static const utility::file::path getFolderFSPath(ref <const maildirStore> store,
const utility::path& folderPath, const FolderFSPathMode mode); const utility::path& folderPath, const FolderFSPathMode mode);
/** Test whether the specified file-system directory corresponds to /** Test whether the specified file-system directory corresponds to

View File

@ -54,7 +54,7 @@ private:
friend class POP3Message; friend class POP3Message;
friend class vmime::creator; // vmime::create <POP3Folder> friend class vmime::creator; // vmime::create <POP3Folder>
POP3Folder(const folder::path& path, POP3Store* store); POP3Folder(const folder::path& path, ref <POP3Store> store);
POP3Folder(const POP3Folder&) : folder() { } POP3Folder(const POP3Folder&) : folder() { }
~POP3Folder(); ~POP3Folder();
@ -108,8 +108,8 @@ public:
ref <folder> getParent(); ref <folder> getParent();
weak_ref <const store> getStore() const; ref <const store> getStore() const;
weak_ref <store> getStore(); ref <store> getStore();
void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL); void fetchMessages(std::vector <ref <message> >& msg, const int options, utility::progressListener* progress = NULL);
@ -129,7 +129,7 @@ private:
void parseMultiListOrUidlResponse(const string& response, std::map <int, string>& result); void parseMultiListOrUidlResponse(const string& response, std::map <int, string>& result);
POP3Store* m_store; weak_ref <POP3Store> m_store;
folder::path m_path; folder::path m_path;
folder::path::component m_name; folder::path::component m_name;

View File

@ -49,7 +49,7 @@ private:
friend class POP3Folder; friend class POP3Folder;
friend class vmime::creator; // vmime::create <POP3Message> friend class vmime::creator; // vmime::create <POP3Message>
POP3Message(POP3Folder* folder, const int num); POP3Message(ref <POP3Folder> folder, const int num);
POP3Message(const POP3Message&) : message() { } POP3Message(const POP3Message&) : message() { }
~POP3Message(); ~POP3Message();
@ -79,11 +79,11 @@ public:
private: private:
void fetch(POP3Folder* folder, const int options); void fetch(ref <POP3Folder> folder, const int options);
void onFolderClosed(); void onFolderClosed();
POP3Folder* m_folder; weak_ref <POP3Folder> m_folder;
int m_num; int m_num;
uid m_uid; uid m_uid;
int m_size; int m_size;

View File

@ -44,84 +44,52 @@ class object
template <class T> friend class utility::ref; template <class T> friend class utility::ref;
template <class T> friend class utility::weak_ref; template <class T> friend class utility::weak_ref;
friend class utility::refManager;
protected: protected:
object(); object();
object(const object&); object(const object&);
object& operator=(const object&);
virtual ~object(); virtual ~object();
#ifndef VMIME_BUILDING_DOC #ifndef VMIME_BUILDING_DOC
/** Add a strong reference to this object. A strong
* reference ensure the object remains alive.
*/
void addStrong() const;
/** Add a weak reference to this object. A weak
* reference helps to resolve circular references.
*/
void addWeak(utility::weak_ref_base* w) const;
/** Release a strong reference to this object.
*
* @return true if the object is not referenced anymore.
*/
void releaseStrong() const;
/** Release a weak reference to this object.
*
* @return true if the object is not referenced anymore.
*/
void releaseWeak(utility::weak_ref_base* w) const;
/** Return a reference to this object. /** Return a reference to this object.
* \warning NEVER CALL THIS FROM A CONSTRUCTOR!
* *
* @return reference to self * @return reference to self
*/ */
ref <object> thisRef(); ref <object> thisRef();
/** Return a reference to this object (const version). /** Return a reference to this object (const version).
* \warning NEVER CALL THIS FROM A CONSTRUCTOR!
* *
* @return reference to self * @return reference to self
*/ */
ref <const object> thisRef() const; ref <const object> thisRef() const;
/** Return a weak reference to this object. /** Return a weak reference to this object.
* \warning NEVER CALL THIS FROM A CONSTRUCTOR!
* *
* @return weak reference to self * @return weak reference to self
*/ */
weak_ref <object> thisWeakRef(); weak_ref <object> thisWeakRef();
/** Return a weak reference to this object (const version). /** Return a weak reference to this object (const version).
* \warning NEVER CALL THIS FROM A CONSTRUCTOR!
* *
* @return weak reference to self * @return weak reference to self
*/ */
weak_ref <const object> thisWeakRef() const; weak_ref <const object> thisWeakRef() const;
/** Return the number of strong refs to this object.
* For debugging purposes only.
*
* @return strong reference count
*/
const int getStrongRefCount() const;
/** Return the number of weak refs to this object. void setRefManager(utility::refManager* mgr);
* For debugging purposes only. utility::refManager* getRefManager() const;
*
* @return weak reference count
*/
const int getWeakRefCount() const;
#endif // VMIME_BUILDING_DOC #endif // VMIME_BUILDING_DOC
private: private:
mutable int m_strongCount; mutable utility::refManager* m_refMgr;
mutable std::vector <utility::weak_ref_base*> m_weakRefs;
}; };

View File

@ -56,7 +56,7 @@ public:
* access platform-dependant objects: sockets, date/time, file system, etc. * access platform-dependant objects: sockets, date/time, file system, etc.
*/ */
class handler class handler : public object
{ {
public: public:
@ -132,11 +132,10 @@ public:
template <class TYPE> template <class TYPE>
static void setHandler() static void setHandler()
{ {
delete (sm_handler); sm_handler = vmime::create <TYPE>();
sm_handler = new TYPE;
} }
static const handler* getHandler() static ref <const handler> getHandler()
{ {
if (!sm_handler) if (!sm_handler)
throw exceptions::no_platform_dependant_handler(); throw exceptions::no_platform_dependant_handler();
@ -146,7 +145,7 @@ public:
private: private:
static handler* sm_handler; static ref <handler> sm_handler;
}; };

View File

@ -58,6 +58,89 @@ public:
}; };
/** Reference counter for shared pointers.
*/
class refCounter
{
public:
refCounter(const long initialValue);
~refCounter();
const long increment();
const long decrement();
const long compareExchange(const long compare, const long exchangeWith);
operator long() const;
private:
long m_value;
};
/** Manage the life cycle of an object.
*/
class refManager
{
public:
refManager(object* obj);
~refManager();
/** Add a strong reference to the managed object.
*/
const bool addStrong();
/** Release a strong reference to the managed object.
* If it is the last reference, the object is destroyed.
*/
void releaseStrong();
/** Add a weak reference to the managed object.
*/
void addWeak();
/** Release a weak reference to the managed object.
* If it is the last weak reference, the manager is destroyed.
*/
void releaseWeak();
/** Return a raw pointer to the managed object.
*
* @return pointer to the managed object
*/
object* getObject();
/** Return the number of strong refs to this object.
* For debugging purposes only.
*
* @return strong reference count
*/
const long getStrongRefCount() const;
/** Return the number of weak refs to this object.
* For debugging purposes only.
*
* @return weak reference count
*/
const long getWeakRefCount() const;
private:
void deleteManager();
void deleteObject();
object* m_object;
refCounter m_strongCount;
refCounter m_weakCount;
};
/** Null reference. /** Null reference.
*/ */
@ -69,7 +152,11 @@ private:
}; };
/** Strong reference (smart pointer). template <class T>
class weak_ref;
/** Shared ownership (strong reference to an object).
*/ */
template <class T> template <class T>
@ -85,7 +172,7 @@ public:
ref(const ref& r) : m_ptr(0) { attach(r); } ref(const ref& r) : m_ptr(0) { attach(r); }
ref(const null_ref&) : m_ptr(0) { } ref(const null_ref&) : m_ptr(0) { }
virtual ~ref() { detach(); } virtual ~ref() throw() { detach(); }
// Allow creating NULL ref (NULL casts to anything*) // Allow creating NULL ref (NULL casts to anything*)
ref(class null_pointer*) : m_ptr(0) { } ref(class null_pointer*) : m_ptr(0) { }
@ -112,12 +199,10 @@ public:
U* p = dynamic_cast <U*>(const_cast <T*>(m_ptr)); U* p = dynamic_cast <U*>(const_cast <T*>(m_ptr));
if (!p) return ref <U>(); if (!p) return ref <U>();
p->addStrong(); if (m_ptr)
m_ptr->getRefManager()->addStrong();
ref <U> r; return ref <U>::fromPtrImpl(p);
r.m_ptr = p;
return r;
} }
// static_cast // static_cast
@ -127,12 +212,10 @@ public:
U* p = static_cast <U*>(const_cast <T*>(m_ptr)); U* p = static_cast <U*>(const_cast <T*>(m_ptr));
if (!p) return ref <U>(); if (!p) return ref <U>();
p->addStrong(); if (m_ptr)
m_ptr->getRefManager()->addStrong();
ref <U> r; return ref <U>::fromPtrImpl(p);
r.m_ptr = p;
return r;
} }
// const_cast // const_cast
@ -142,12 +225,10 @@ public:
U* p = const_cast <U*>(m_ptr); U* p = const_cast <U*>(m_ptr);
if (!p) return ref <U>(); if (!p) return ref <U>();
m_ptr->addStrong(); if (m_ptr)
m_ptr->getRefManager()->addStrong();
ref <U> r; return ref <U>::fromPtrImpl(p);
r.m_ptr = p;
return r;
} }
// Implicit downcast // Implicit downcast
@ -155,7 +236,7 @@ public:
operator ref <const U>() const operator ref <const U>() const
{ {
if (m_ptr) if (m_ptr)
m_ptr->addStrong(); m_ptr->getRefManager()->addStrong();
ref <const U> r; ref <const U> r;
r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast) r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast)
@ -167,7 +248,7 @@ public:
operator ref <U>() operator ref <U>()
{ {
if (m_ptr) if (m_ptr)
m_ptr->addStrong(); m_ptr->getRefManager()->addStrong();
ref <U> r; ref <U> r;
r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast) r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast)
@ -181,7 +262,7 @@ public:
U* ptr = other.m_ptr; // will type check at compile-time (prevent from implicit upcast) U* ptr = other.m_ptr; // will type check at compile-time (prevent from implicit upcast)
if (ptr) if (ptr)
ptr->addStrong(); ptr->getRefManager()->addStrong();
detach(); detach();
@ -194,12 +275,9 @@ public:
operator ref <const T>() const operator ref <const T>() const
{ {
if (m_ptr) if (m_ptr)
m_ptr->addStrong(); m_ptr->getRefManager()->addStrong();
ref <const T> r; return ref <const T>::fromPtrImpl(m_ptr);
r.m_ptr = m_ptr;
return r;
} }
// Copy // Copy
@ -230,22 +308,50 @@ public:
*/ */
static ref <T> fromPtr(T* const ptr) static ref <T> fromPtr(T* const ptr)
{ {
if (ptr) return ref <T>::fromPtrImpl(ptr);
ptr->addStrong(); }
ref <T> r; static ref <const T> fromPtrConst(const T* const ptr)
{
return ref <const T>::fromPtrImpl(ptr);
}
static ref <T> fromWeak(weak_ref <T> wr)
{
refManager* mgr = wr.getManager();
if (mgr && mgr->addStrong())
return ref <T>::fromPtrImpl(dynamic_cast <T*>(mgr->getObject()));
else
return ref <T>();
}
static ref <const T> fromWeakConst(weak_ref <const T> wr)
{
refManager* mgr = wr.getManager();
if (mgr && mgr->addStrong())
return ref <const T>::fromPtrImpl(dynamic_cast <const T*>(mgr->getObject()));
else
return ref <const T>();
}
protected:
template <class U>
static ref <U> fromPtrImpl(U* ptr)
{
ref <U> r;
r.m_ptr = ptr; r.m_ptr = ptr;
return r; return r;
} }
protected:
void detach() void detach()
{ {
if (m_ptr) if (m_ptr)
{ {
m_ptr->releaseStrong(); m_ptr->getRefManager()->releaseStrong();
m_ptr = 0; m_ptr = 0;
} }
} }
@ -254,7 +360,7 @@ protected:
void attach(U* const ptr) void attach(U* const ptr)
{ {
if (ptr) if (ptr)
ptr->addStrong(); ptr->getRefManager()->addStrong();
detach(); detach();
@ -265,7 +371,7 @@ protected:
void attach(const ref <U>& r) void attach(const ref <U>& r)
{ {
if (r.m_ptr) if (r.m_ptr)
r.m_ptr->addStrong(); r.m_ptr->getRefManager()->addStrong();
detach(); detach();
@ -329,169 +435,64 @@ bool operator!=(const null_ref&, const ref <T>& r)
/** Base class for weak references.
*/
class weak_ref_base
{
friend class vmime::object; // calls 'notifyObjectDestroyed'
protected:
weak_ref_base() { }
weak_ref_base(const weak_ref_base&) { }
virtual ~weak_ref_base() { }
virtual void notifyObjectDestroyed() = 0;
};
/** Weak reference. /** Weak reference.
* Avoid circular references. * Avoid circular references.
*/ */
template <class T> template <class T>
class weak_ref : public weak_ref_base class weak_ref
{ {
public: public:
template <class U> friend class weak_ref; template <class U> friend class weak_ref;
weak_ref() : m_ptr(0) { } weak_ref() : m_mgr(0) { }
weak_ref(const ref <T>& r) : m_ptr(0) { attach(r); } weak_ref(const ref <T>& r) : m_mgr(0) { attach(r); }
weak_ref(const weak_ref& r) : weak_ref_base(), m_ptr(0) { attach(r); } weak_ref(const weak_ref& r) : m_mgr(0) { attach(r); }
weak_ref(const null_ref&) : m_ptr(0) { } weak_ref(const null_ref&) : m_mgr(0) { }
weak_ref(T* const p) : m_ptr(0) { attach(p); } weak_ref(class null_pointer*) : m_mgr(0) { }
~weak_ref() { detach(); } ~weak_ref() { detach(); }
/** Return the manager for the object.
// Access to wrapped object *
// operator const T*() const { return m_ptr; } * @return pointer to the object which manages the object
operator const void*() const { return m_ptr; } * or NULL if the weak reference points to nothing
*/
T& operator *() { return *m_ptr; } refManager* getManager()
const T& operator *() const { return *m_ptr; }
T* operator ->() { return m_ptr; }
const T* operator ->() const { return m_ptr; }
const T* const get() const { return m_ptr; }
T* const get() { return m_ptr; }
const bool operator !() const { return m_ptr == NULL; }
// dynamic_cast
template <class U>
weak_ref <U> dynamicCast() const
{ {
U* p = dynamic_cast <U*>(const_cast <T*>(m_ptr)); return m_mgr;
if (!p) return weak_ref <U>();
weak_ref <U> r;
p->addWeak(&r);
r.m_ptr = p;
return r;
} }
// static_cast /** Try to acquire a strong reference to the object (const version).
template <class U> *
weak_ref <U> staticCast() const * @return strong reference or null reference if the
* object is not available anymore
*/
ref <const T> acquire() const
{ {
U* p = static_cast <U*>(const_cast <T*>(m_ptr)); return ref <const T>::fromWeakConst(*this);
if (!p) return weak_ref <U>();
weak_ref <U> r;
p->addWeak(&r);
r.m_ptr = p;
return r;
} }
// const_cast /** Try to acquire a strong reference to the object.
template <class U> *
weak_ref <U> constCast() const * @return strong reference or null reference if the
* object is not available anymore
*/
ref <T> acquire()
{ {
U* p = const_cast <U*>(m_ptr); return ref <T>::fromWeak(*this);
if (!p) return weak_ref <U>();
weak_ref <U> r;
p->addWeak(&r);
r.m_ptr = p;
return r;
}
// Implicit downcast
template <class U>
operator weak_ref <const U>()
{
weak_ref <const U> r;
if (m_ptr)
m_ptr->addWeak(&r);
r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast)
return r;
}
// Implicit downcast
template <class U>
operator weak_ref <U>()
{
weak_ref <U> r;
if (m_ptr)
m_ptr->addWeak(&r);
r.m_ptr = m_ptr; // will type check at compile-time (prevent from implicit upcast)
return r;
}
template <class U>
weak_ref <T>& operator=(const weak_ref <U>& other)
{
U* ptr = other.m_ptr; // will type check at compile-time (prevent from implicit upcast)
if (ptr)
ptr->addWeak(this);
detach();
m_ptr = ptr;
return *this;
}
ref <T> toStrong()
{
if (m_ptr == NULL)
return ref <T>();
return ref <T>::fromPtr(m_ptr);
} }
// Implicit non-const => const conversion // Implicit non-const => const conversion
operator weak_ref <const T>() const operator weak_ref <const T>() const
{ {
if (m_mgr)
m_mgr->addWeak();
weak_ref <const T> r; weak_ref <const T> r;
r.m_mgr = m_mgr;
if (m_ptr)
m_ptr->addWeak(&r);
r.m_ptr = m_ptr;
return r; return r;
} }
@ -499,12 +500,11 @@ public:
template <class U> template <class U>
operator weak_ref <const U>() const operator weak_ref <const U>() const
{ {
if (m_mgr)
m_mgr->addWeak();
weak_ref <const U> r; weak_ref <const U> r;
r.m_mgr = m_mgr;
if (m_ptr)
m_ptr->addWeak(&r);
r.m_ptr = m_ptr;
return r; return r;
} }
@ -516,58 +516,42 @@ public:
return *this; return *this;
} }
// NULL-pointer comparison
bool operator==(const class null_pointer*) const { return m_ptr == 0; }
bool operator!=(const class null_pointer*) const { return m_ptr != 0; }
private: private:
void notifyObjectDestroyed()
{
m_ptr = 0;
}
void detach() void detach()
{ {
if (m_ptr) if (m_mgr)
{ {
m_ptr->releaseWeak(this); m_mgr->releaseWeak();
m_ptr = 0; m_mgr = 0;
} }
} }
void attach(const ref <T>& r) void attach(const ref <T>& r)
{ {
if (r.m_ptr) if (r.m_ptr)
r.m_ptr->addWeak(this); r.m_ptr->getRefManager()->addWeak();
detach(); detach();
m_ptr = r.m_ptr; if (r.m_ptr)
m_mgr = r.m_ptr->getRefManager();
else
m_mgr = 0;
} }
void attach(const weak_ref& r) void attach(const weak_ref& r)
{ {
if (r.m_ptr) if (r.m_mgr)
r.m_ptr->addWeak(this); r.m_mgr->addWeak();
detach(); detach();
m_ptr = r.m_ptr; m_mgr = r.m_mgr;
}
void attach(T* const p)
{
if (p)
p->addWeak(this);
detach();
m_ptr = p;
} }
T* m_ptr; refManager* m_mgr;
}; };