Window live resize: which edge is being dragged?

2014-01-23 Thread Oleg Krupnov
Is there a way to tell which edge or corner of the window is being
dragged by the user during the “live resize” mode?

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to tell if a file is writable in sandboxed mode?

2013-11-13 Thread Oleg Krupnov
I am not sure what you mean by the failure, could you explain please?

In my experience, if you have read-write sandbox access to a url, you
can create bookmark with and without the
NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess flag, and it
will create different NSData objects. And if you have read-only
sandbox access to a url, the both bookmarks created with and without
the flag, will produce identical NSData objects. That’s the point of
my method, to test the potentially read-write NSData against the
afore-known read-only NSData.

And as always, my design is asked to be reconsidered. No one wants to
reconsider design of the sandbox itself, that *IS* creating so much
pain in the ass for everyone :) I need this bookmark access testing
because the sandbox is buggy on OSX Mavericks and I need to work
around it. Namely, unlike previously, only read-only access is granted
to a folder if you open certain folders by dragging them to your app’s
*window* (as opposed to dragging it to the app’s icon in the Dock or
opening via NSOpenPanel). BTW this bug affects many apps in the App
Store which need to write and delete files in folders. I have already
filed this bug to Apple and in the meantime, I need to give some kind
of instruction to the user. To do this I need to know if there is no
access due to file permissions (normal case) or due to sandbox
(Mavericks bug).



On Wed, Nov 13, 2013 at 7:51 PM, Mike Abdullah  wrote:
>
> On 13 Nov 2013, at 11:46, Oleg Krupnov  wrote:
>
>> Thanks for new info, but no, unfortunately, this NSURLIsWritableKey
>> cannot discriminate between "not writable due to file permissions” and
>> “not writable due to sandbox” cases. The both cases are "not writable"
>> for the NSURLIsWritableKey.
>>
>> I’ve found another workaround but not sure how reliable it is, because
>> the bookmark data is an opaque object and its implementation is not
>> clear.
>>
>> Namely, when I need to test a URL for writability, I create two
>> bookmark datas from the url using the -[NSURL
>> bookmarkDataWithOptions:…] method. The first is created with
>> NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess option, and
>> another one without it.
>>
>> Then I test whether the two NSData objects that I obtain are
>> byte-by-byte identical (-[NSData isEqualToData:]), and if yes, then I
>> assume this is a read-only bookmark. Otherwise, I assume this bookmark
>> is writeable, from sandboxing point of view.
>>
>> The weak point of this method is the assumption that the obtained
>> bookmark NSData is always identical if the path and its sandbox access
>> mode do not change. I could theoretically get a false positive if I
>> get a different NSData object while the url is still read-only. The
>> false negative seems less likely (that I get an byte-by-byte identical
>> NSData object while the URL is not read-only any more.)
>>
>> If I could be sure that bookmark data doesn’t involve any changeable
>> data (like time stamps etc.), this could be a reliable method.
>
> Hmmm, that sounds very ropey to me. In my experience 
> NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess has little to no effect 
> on how the file is handled at a write level. i.e. if you have read-only 
> access to the file, creating the bookmark will fail since it tries to achieve 
> write access to the file.
>
> I think you should back up and consider your design. The sandbox isn’t really 
> designed to be tested in this manner. Instead your app is supposed to track 
> things and have a decent idea of which resources it ought to have access to, 
> and which not.
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to tell if a file is writable in sandboxed mode?

2013-11-13 Thread Oleg Krupnov
Thanks for new info, but no, unfortunately, this NSURLIsWritableKey
cannot discriminate between "not writable due to file permissions” and
“not writable due to sandbox” cases. The both cases are "not writable"
for the NSURLIsWritableKey.

I’ve found another workaround but not sure how reliable it is, because
the bookmark data is an opaque object and its implementation is not
clear.

Namely, when I need to test a URL for writability, I create two
bookmark datas from the url using the -[NSURL
bookmarkDataWithOptions:…] method. The first is created with
NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess option, and
another one without it.

Then I test whether the two NSData objects that I obtain are
byte-by-byte identical (-[NSData isEqualToData:]), and if yes, then I
assume this is a read-only bookmark. Otherwise, I assume this bookmark
is writeable, from sandboxing point of view.

The weak point of this method is the assumption that the obtained
bookmark NSData is always identical if the path and its sandbox access
mode do not change. I could theoretically get a false positive if I
get a different NSData object while the url is still read-only. The
false negative seems less likely (that I get an byte-by-byte identical
NSData object while the URL is not read-only any more.)

If I could be sure that bookmark data doesn’t involve any changeable
data (like time stamps etc.), this could be a reliable method.

Ideas?


On Sat, Nov 9, 2013 at 6:04 PM, Mike Abdullah  wrote:
> Does querying for NSURLIsWritableKey give you any more info?
>
> On 8 Nov 2013, at 16:31, Oleg Krupnov  wrote:
>
>> I’m trying to use -[NSFileManager isWritableFileAtPath:], but when it
>> returns NO, I’d like to know if it’s “no” because the app simply
>> doesn’t have access to this path due to sandboxing, or is it “no"
>> because the file doesn’t have write permissions set in its file
>> attributes?
>>
>> Is there a way to discriminate these two cases?
>>
>> Or more generally, is there a way to tell that an app does or does not
>> have access to some file because of *sandboxing* (as opposed to file
>> attributes)?
>>
>> Thanks!
>>
>> ___
>>
>> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>> https://lists.apple.com/mailman/options/cocoa-dev/mabdullah%40karelia.com
>>
>> This email sent to mabdul...@karelia.com
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

How to tell if a file is writable in sandboxed mode?

2013-11-08 Thread Oleg Krupnov
I’m trying to use -[NSFileManager isWritableFileAtPath:], but when it
returns NO, I’d like to know if it’s “no” because the app simply
doesn’t have access to this path due to sandboxing, or is it “no"
because the file doesn’t have write permissions set in its file
attributes?

Is there a way to discriminate these two cases?

Or more generally, is there a way to tell that an app does or does not
have access to some file because of *sandboxing* (as opposed to file
attributes)?

Thanks!

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Unmounting/ejecting volumes in sandboxed mode

2013-08-12 Thread Oleg Krupnov
Further experiments show that some disks can be ejected under sandbox,
while others cannot. For example, CD, USB sticks, DMGs and some
external drives can be ejected/unmounted, while other external drives
and internal partitions cannot. The rule isn't that simple and seems
to have many exceptions. I've found that some other developers have
discovered this to be a bug of sandbox and filed it to Apple which
ostensibly agreed that was a bug but they haven't fixed it so far.

> Probably not. That seems like a pretty serious operation; I would not
> expect it to be available to sandboxed applications.

With all respect, this sounds like again if Apple doesn't allow
something, ergo you don't need it. There are many situations when apps
may have legitimate needs to eject disks. If it requires a curated
entitlement, Apple should have provided one. It is not a kind of case
when an entitlement would be technically difficult or impossible to
provide. So I tend to think it's a bug indeed.

On Mon, Aug 12, 2013 at 8:21 PM, Kyle Sluder  wrote:
> On Mon, Aug 12, 2013, at 08:28 AM, Oleg Krupnov wrote:
>
>> The "system.volume.internal.unmount entitlement" is not documented,
>
> This is an authorization right, not a sandbox entitlement.
>
>> and when I tried to add it to the list of entitlements, the app fails
>> to start at all, saying not enough permissions.
>>
>> What's going on? Is there a way to eject/unmount disks in sandboxed mode?
>
> Probably not. That seems like a pretty serious operation; I would not
> expect it to be available to sandboxed applications.
>
> --Kyle Sluder
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Unmounting/ejecting volumes in sandboxed mode

2013-08-12 Thread Oleg Krupnov
I've run across an unexpected and undocumented problem, and couldn't
google anything on it.

It seems that if an app is sandboxed, it is not permitted to eject
disks or unmount volumes.

I tried -[NSWorkspace unmountAndEjectDeviceAtPath:],
FSUnmountVolumeAsync / FSEjectVolumeAsync, DADiskUnmount / DADiskEject
but all I get is failure with a message like "Error
Domain=NSOSStatusErrorDomain Code=-47 "The operation couldn’t be
completed. (OSStatus error -47.)" (fBsyErr: File is busy (delete))"

and in Console I see "com.apple.SecurityServer[16]: Sandbox denied
authorizing right 'system.volume.internal.unmount' by client …"

The "system.volume.internal.unmount entitlement" is not documented,
and when I tried to add it to the list of entitlements, the app fails
to start at all, saying not enough permissions.

What's going on? Is there a way to eject/unmount disks in sandboxed mode?

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Exiting non-POSIX threads?

2013-07-31 Thread Oleg Krupnov
> Which is why he specifically mentioned the option of an external watchdog 
> process.

This seems like an overkill. Every app needs some kind of crash
reporting, are you suggesting to accompany each app with a watchdog
process? Besides, the user might think your app is a spyware when he
sees the watchdog process in Activity Monitor.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Exiting non-POSIX threads?

2013-07-30 Thread Oleg Krupnov
Hi Ken,

> Let the app crash.  Let the CrashReporter tell the user that it crashed.  If 
> you want to receive the crash report yourself, use an external watchdog 
> process or collect the crash report file on next launch.

I'd agree that this approach technically is more correct. One downside
of it though is that the user should launch the crashed app at least
one more time. Hopefully, it's not going to be a crash on first launch
followed by immediate trashing of the app :)

So it boils down to these questions:

1. What is the correct way of terminating the app if the exception
happens in the main thread? I need the system Crash Reporter to save
the context and stack trace of the original problem, not of some
exception handler.

2. Will it work in sandboxed mode? The folder with crash reports may
appear unaccessible.

P.S. It dawned at me that I could relaunch another instance of the app
(using a shell script) before my app terminates, in this way relying
on the user to do this is not needed.

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Exiting non-POSIX threads?

2013-07-30 Thread Oleg Krupnov
Thanks Ken,

> However, you're not supposed to let exceptions escape from blocks which you 
> submit to dispatch queues.  That's documented in the link I gave in my 
> previous reply.

Yes, thanks for pointing it out, but let me note that this is not
consistent with other parts of the AppKit. When an exception happens
in the main thread, it is logged to the console and quietly absorbed
without any additional action on my part.

Now if the exception happens in a non-main thread, I am obliged to
catch it or otherwise the app will be instantly terminated. This is
inconsistent. I may not be using or even expecting any exceptions in
the thread, but merely use some NSAssert's and want to report logical
errors in my code. Putting explicit @try/@catch in every thread with
NSAssert's seems like an overkill or even something I should not rely
upon, because I want to write a catch-all for problems, including my
own bugs, such as forgetting to wrap the thread in @try/@catch.

> If you exit a thread that you don't own, you may screw up your app's ability 
> to present a dialog.  Perhaps AppKit relies on that thread.  Perhaps the 
> thread held a crucial resource and other threads will deadlock when they try 
> to access it.

I'd disagree. This thread has already crashed and its exception was
not caught, and so the thread is about to be terminated with or
without my intervention. Killing it myself would hardly produce any
side effects. I just want to prevent the entire app from termination
and so far it seems darn impossible.

> All in all, what you're doing seems like a bad idea.

Maybe but what is the right solution to this?
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Exiting non-POSIX threads?

2013-07-29 Thread Oleg Krupnov
Thanks for your answer, Steve, but the problem remains.

In my case, the exception has already been thrown inside the block and
I cannot catch it or modify it in any way in my handler. I'm basically
writing an uncaught exception handler. My app should show a crash
report window and then terminate itself.

The problem is that if the exception happens in another thread, the
app gets instantly terminated by the system after my exception handler
(unlike exceptions in the main thread that are automatically
absorbed), unless I terminate the crashed thread manually. [NSThread
exit] worked with NSThreads, but with GCD threads (starting from
start_wqthread), it's causing the signal.


On Mon, Jul 29, 2013 at 12:27 PM, Steve Sisak  wrote:
> At 11:34 AM +0300 7/29/13, Oleg Krupnov wrote:
>>
>> However for GCD thread (created with dispatch_async()) I get the
>> following signal:
>>
>> pthread_exit() may only be called against threads created via
>> pthread_create()
>>
>> Is there a way to handle this case?
>
>
> Just return from the block you passed to dispatch_async()
>
>
>> Is there a way to exit a GCD thread?
>
>
> There's no such thing as a "GCD thread" only queues.
>
> (OK, there's a pool of threads that GCD uses to service queues, but you
> don't own them)
>
>
>> At least, is there a way of telling POSIX threads from GCD / other
>> threads?
>
>
> WAYRTTD?
>
> Exiting threads is bad form in general -- if you're really writing an
> exception handler, catch it at the outermost level and just return so the
> thread terminates normally.
>
> Same for your outer block in GCD.
>
> HTH,
>
> -Steve
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Exiting non-POSIX threads?

2013-07-29 Thread Oleg Krupnov
I'm writing an exception handler where I want to terminate a crashed
thread without terminating the entire process. Before GCD I used the
following code:


if ([NSThread currentThread] != [NSThread mainThread])
{
   [NSThread exit];
}

However for GCD thread (created with dispatch_async()) I get the
following signal:

pthread_exit() may only be called against threads created via pthread_create()


Is there a way to handle this case?

Is there a way to exit a GCD thread?

At least, is there a way of telling POSIX threads from GCD / other threads?
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSNotFound signed???

2013-06-12 Thread Oleg Krupnov
> This has nothing to do with the amount of available RAM. The limitation is 
> with the virtual memory system.
> If you can have 2^64 bytes of address space, you can a max store "2^64 / 
> sizeof(void *)" pointers.

You misunderstood, I wasn't talking about RAM. It was merely an
illustration of how an assumption that seemed justified basing on some
then current technical limits, in hindsight turned out ridiculous and
crippling after the technical limits were pushed further. Never mind.

> If you have sparse array, so just don't write it using NSNotFound. We are 
> talking about a well defined class and well defined API, not a potential non 
> existing API that can use the wrong constant.

That's exactly the pitfall that I felt into, and that's the point of
my original post. I thought it was safe to use NSNotFound with my
classes because it is so commonly used with NSUInteger array indexes
in the framework, but it turns out to be unsafe, and without any
documented cautions.

>> One higher bit is actually twice as many elements. Why having
>> NSUInteger at all if you can't use more than NSIntegerMax? This
>> doesn't seem right.
>
> Because you want to use an unsigned number to defined the number of element 
> (having a negative number of elements does not make sense), and it is 
> pointless and inefficient to to defined and used a 56bit integer type on 
> actual architectures.

You seem to be ardently defending the idea that it's somehow okay to
lose half of possible array indexes just because. I admit there may be
good reasons for this, but I'm yet to see why exactly.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: NSNotFound signed???

2013-06-12 Thread Oleg Krupnov
> there isn't enough address space to create a NSArray containing even 
> NSIntegerMax pointers.

I knew someone will say this. Who needs more than 640 KB RAM after
all? :) © Bill Gates

What if I have sparse array etc.

One higher bit is actually twice as many elements. Why having
NSUInteger at all if you can't use more than NSIntegerMax? This
doesn't seem right.

Anyway thanks for your time, Quincey!

On Wed, Jun 12, 2013 at 10:52 AM, Quincey Morris
 wrote:
> On Jun 12, 2013, at 00:42 , Quincey Morris
>  wrote:
>
> If you archive a 64-bit NSNotFound, it's no longer NSNotFound when
> unarchived on a 32-bit architecture, and vice versa.
>
>
> Oops, just to clarify:
>
> I don't mean there's anything wrong with the archiving or unarchiving per
> se.
>
> It's no longer NSNotFound when you encode/decode a NSUInteger/NSInteger
> variable, because there'll be truncation or "incorrect" sign extension of
> the scalar value, in one direction or the other.
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

NSNotFound signed???

2013-06-12 Thread Oleg Krupnov
I've just been shocked to find out that NSNotFound is defined by the
framework as NSIntegerMax, that is maximal value of *SIGNED* integer,
which in 64 bit architecture is 0x7fff.

I used to think that it should be NSUIntegerMax, that is the maximal
value of *UNSIGNED* integer, corresponding to 0x.

It had to be so because NSNotFound value is used in many places of the
system framework for working with array indexes, for example,
-[NSArray indexOfObject:] returns unsigned NSUInteger indexes, *BUT*
it returns NSNotFound if the element is not found.

But NSNotFound should be a valid index in the middle of possible
unsigned integer range! It means that even though the NSArray allows
NSUIntegerMax of elements, you can actually use only NSIntegerMax
elements, because starting from NSIntegerMax you will get screwed up
by things like indexOfObject:

How come?
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: NSMapTable with C strings as keys

2013-05-28 Thread Oleg Krupnov
> Why not just create NSString wrappers? By using the 
> -initWithBytesNoCopy:length:encoding:freeWhenDone: method you can avoid it 
> copying the actual C string characters, it literally just becomes a thin 
> wrapper.

In my case it's more about extra calls than extra memory but thanks! Didn't 
know about this.

> For the sake of avoiding something you *assume* to be slow, or inefficient, 
> you've taken the discussion in a direction that is vastly more complicated.


The code in question is frequently used in many places so I think it's worth 
optimization. 

This KISS school of thought has brought Microsoft to building the slow and 
inefficient .NET technology, and it's had a hard time persuading everybody and 
his dog that hardware is evolving faster than they right inefficient code, so 
it was "ok", but ultimately this approach failed. 

While I generally agree that premature optimization is evil, I do not 
understand why I cannot or shouldn't always keep in mind the cost of things I 
am using, and consider more efficient approaches, especially when they are 
simple. (This time it has turned out not simple and not even efficient, so I 
changed my mind). 

The profiler is not a panacea; when you have hundreds of small, 
not-so-efficient pieces of code like this, all you see in profiler is a long 
list of small consumers, totaling in heavy use of objc runtime calls. 

On May 29, 2013, at 1:46 AM, Graham Cox  wrote:

> 
> On 28/05/2013, at 3:46 PM, Oleg Krupnov  wrote:
> 
>> I'd like to have a dictionary using C strings as keys (because I
>> already have const char* strings and would like to spare on creating
>> NSString wrappers)
> 
> 
> 
> 
> K.I.S.S.! If you can prove this approach is a problem by actual profiling, 
> then OK, then you can talk about a more complex solution.
> 
> 
> --Graham
> 
> 
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: NSMapTable with C strings as keys

2013-05-28 Thread Oleg Krupnov
> If you're going to do that, why bother with an NSMapTable at all? Just store 
> your pointers in a C array.

The string pointers can be different, but they can contain identical
string keys, resulting in identical values. I wanted to find values by
in a more efficient way than dumb array iteration, say, like binary
tree search which is probably used in NSDictionary or NSMapTable.

> It's not useful to pursue this line of thinking without benchmarks.

Now I guess you're right. I just didn't know it was going to be that
complicated. I thought it was pure benefit and cheap. I am reverting
to using NSDictionary.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: NSMapTable with C strings as keys

2013-05-28 Thread Oleg Krupnov
I just made the following experiment:

I specified a hash method for my NSMapTable, but it always returns 0.
This seems to force the NSMapGet to always use key comparison for
searching for elements, as hash is always "not unique".

Is this a good idea?

Let me think. The keys are quite short strings, like 5-10 chars.

If we take the expense of calculating hash once for each search, then
comparing hash values is very quick, plus a few string comparisons in
the end if hash is not unique

If we spare on calculating hash, we will compare strings on each
ramification of the binary tree. Besides, it seems that isEqual method
returns BOOL which means the keys will not be sorted, which makes
binary tree search impossible? In this case hash seems the only sane
solution for NSMapTable. Am I right?



On Tue, May 28, 2013 at 10:03 AM, Jean-Daniel Dupas
 wrote:
>
> Le 28 mai 2013 à 08:25, Oleg Krupnov  a écrit :
>
>> Hi Jens,
>>
>> I guess you may be right. But… two questions in this regard:
>>
>> 1. I thought that "isEqual" method is alternative to "hash" method,
>> because searching by key and searching by hash are two mutually
>> exclusive methods of looking up values, aren't they?
>>
>
> No, they aren't. The hash is used to speed up the lookup.
> The HashTable first uses the hash to find in which bucket the element is, and 
> as the hash is not guarantee to be unique, it then use the isEqual method to 
> determine what element in this bucket in the one you are looking for.
>
>> 2. What hash function you'd suggest in my case, that would calculate
>> unsigned int on output, for C strings? Because calculating hash
>> functions (such as md5) may be computationally expensive, which could
>> undermine my entire idea of sparing extra few calls on creating
>> NSStrings :)
>
> The main issue with using c string, is memory management of your keys. 
> NSString does that using ref counting, but you will have to take care of 
> everything if you are using C string.
> Avoiding NSString without being sure this will impact the performance is just 
> "premature optimization".
>
> That said, there is 2 famous hash functions that are usually used for this 
> kind of hashing: CityHash (http://code.google.com/p/cityhash/) and MurmurHash 
> (http://code.google.com/p/smhasher/)
>
>> Thanks!
>>
>> On Tue, May 28, 2013 at 9:08 AM, Jens Alfke  wrote:
>>>
>>> On May 27, 2013, at 10:46 PM, Oleg Krupnov  wrote:
>>>
>>> Now, the problem is that sometimes when I try to get a value from the
>>> table, the MapTableKeyComparator function is not called at all, and
>>> NSMapGet returns NULL, thought immediate dump of the table shows that
>>> all previous records are perfectly present in the table.
>>>
>>>
>>> Probably because you haven’t implemented a hash function, only an equals
>>> function. I’m guessing NSMapTable’s default hash function merely hashes the
>>> key pointer itself, which means that if you pass it a different pointer to
>>> an equal C string, it won’t find anything.
>>>
>>> —Jens
>>>
>>
>> ___
>>
>> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>> https://lists.apple.com/mailman/options/cocoa-dev/devlists%40shadowlab.org
>>
>> This email sent to devli...@shadowlab.org
>
> -- Jean-Daniel
>
>
>
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSMapTable with C strings as keys

2013-05-27 Thread Oleg Krupnov
Hi Jens,

I guess you may be right. But… two questions in this regard:

1. I thought that "isEqual" method is alternative to "hash" method,
because searching by key and searching by hash are two mutually
exclusive methods of looking up values, aren't they?

2. What hash function you'd suggest in my case, that would calculate
unsigned int on output, for C strings? Because calculating hash
functions (such as md5) may be computationally expensive, which could
undermine my entire idea of sparing extra few calls on creating
NSStrings :)

Thanks!

On Tue, May 28, 2013 at 9:08 AM, Jens Alfke  wrote:
>
> On May 27, 2013, at 10:46 PM, Oleg Krupnov  wrote:
>
> Now, the problem is that sometimes when I try to get a value from the
> table, the MapTableKeyComparator function is not called at all, and
> NSMapGet returns NULL, thought immediate dump of the table shows that
> all previous records are perfectly present in the table.
>
>
> Probably because you haven’t implemented a hash function, only an equals
> function. I’m guessing NSMapTable’s default hash function merely hashes the
> key pointer itself, which means that if you pass it a different pointer to
> an equal C string, it won’t find anything.
>
> —Jens
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

NSMapTable with C strings as keys

2013-05-27 Thread Oleg Krupnov
I'd like to have a dictionary using C strings as keys (because I
already have const char* strings and would like to spare on creating
NSString wrappers) and C structures as values.

I thought using NSMapTable would be a good idea for this.

Here is my code:

// function for comparing string keys
static BOOL MapTableKeyComparator(NSMapTable* table, const void* key1,
const void* key2)
{
int result = strcmp((const char*)key1, (const char*)key2);
return result == 0;
}


NSMapTable* _table;

…

NSMapTableKeyCallBacks keyCallbacks = NSNonOwnedPointerMapKeyCallBacks;

keyCallbacks.isEqual = MapTableKeyComparator;

NSMapTableValueCallBacks valueCallbacks = NSNonOwnedPointerMapValueCallBacks;

_table = NSCreateMapTable(keyCallbacks, valueCallbacks, 0);

…

NSMapInsert(_table, name, value);

…

value = NSMapGet(_table, name);


Now, the problem is that sometimes when I try to get a value from the
table, the MapTableKeyComparator function is not called at all, and
NSMapGet returns NULL, thought immediate dump of the table shows that
all previous records are perfectly present in the table. The bug
happens sporadically, at different moments. Sometimes it happens at
the line of code where it perfectly worked on last debug session.

What could be wrong?

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: ^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov

> 
> On the other hand, delegates add the problem that they desiccate the code for 
> dealing with the results from the code for setting up the request in the 
> first place.  I would consider that a much much much higher penalty than 
> having to a bit careful about retain cycles.
> 

You are correct, and that was why I switched ruthlessly to blocks instead of 
delegates for callbacks... Until I found this nasty problem with retain cycles, 
which doesn't actually have an elegant solution, and the workarounds leave ugly 
scars in your code and an uneasy feeling of suspicion to every line of your 
code in blocks. 

In fact, blocks only give you an illusion of all code in one place, but just as 
with delegates, it is "dissected" in time, and personally I always find it more 
difficult to read code with blocks, because it takes me an effort to understand 
the context the code will ge running in, across the block scope. Now if you add 
the necessity to think about retain cycles, it's pretty much a nightmare. 

After some time of using blocks, after their novelty worn off, personally I 
don't find them so much more convenient for callbacks as they initially seemed 
(even if there were no retain cycles, which are there, don't forget). It is not 
always relevant to place the callback code in the same place where I set up the 
worker object, and I often find myself calling a single method in the block 
that does the callback down the code, like I would do with delegates. Besides, 
it's quite tricky with blocks if you need to cancel the previous worker and 
replace it with a new one, whereas with delegates you can simply retain the 
current worker and compare it with the callback's sender. 

All in all I come to personally find delegates more elegant and honest than 
blocks for callbacks. Am I alone here? :)
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: ^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov

> I understand the problem you're describing (and yes, I've had a couple of 
> memory leaks resulting from it) but I don't understand how you think it's 
> breaking encapsulation.

The encapsulation is broken by the fact that you can't place whatever code you 
need in the callback block and have to always remember about internal 
implementation of blocks, and its possible implications and side effects, even 
for the simplest cases. It's definitely not something you'd want to focus on, 
given that blocks were called to make life easier, not harder. Implicit 
side-effects are always harder to track and debug. 


> 
> In my code, most of the places I use a block as an onXXX property value it's 
> going to be called exactly once. What I do then is, in the caller, set the 
> corresponding _onXXX ivar to nil after calling through it, to break cycles.
> 

I made it clear in the subject that I was talking about callbacks. There are 
perhaps a number of cases (iterators, threading) where blocks are not copied 
and seem to be perfectly fine. 
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: ^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov


Yes, this is jumping through hoops, and even then you are not entirely safe. 
How about referencing ivars from blocks? How about referencing other objects 
that may in their turn reference self etc.? You have to keep it all in mind and 
constantly fight with the side-effects by adding more crappy hoops to your 
code. And it is a problem that does not even exist with delegates. 

On Apr 25, 2013, at 8:29 PM, Jens Alfke  wrote:

> 
> On Apr 25, 2013, at 9:54 AM, Lee Ann Rucker  wrote:
> 
>> MyWeakRef *weakRef = [MyWeakRef weakRefFromObject:self];
>> 
>> ^() = {
>>  Foo *wself = [weakRef originalObject];
>>  // wself may be nil, that's cool because we only want to doStuff if 'self' 
>> is still around.
>>  [wself doStuff];
>> }
> 
> It's easier to just use the __weak attribute, if you're using ARC:
> 
> __weak Foo *weakRef = self;
> ^() = {
>   Foo *wself = weakRef;
>   // wself may be nil, that's cool because we only want to doStuff if 
> 'self' is still around.
>   [wself doStuff];
> }
> 
> Still, I think this is what Oleg called "jumping through hoops". You and I 
> just don't think it's a very significant hoop :)
> 
> —Jens
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: ^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov
The compiler indeed warns, but only for ARC projects, and for non-ARC
projects it perfectly allows blocks to create retain cycles without
any warnings, even Xcode's Analyze doesn't help.

Besides, I'm afraid the compiler is not always capable to detect all
such dangerous situations even with ARC on.

So I am afraid it ends up with lots of retain cycles in virtually
every project that uses blocks, but programmers just don't notice
and/or just don't care. Do you often check your projects for leaks of
this kind? You will be surprised if you do try.

My point remains: blocks are dangerous and there is no easy way to
ensure they are safe. You can't avoid referencing "self" in blocks,
because it is the very point of almost every callback block. So you
have to every time to remind yourself to jump through hoops to avoid
the retain cycles. Nah.



On Thu, Apr 25, 2013 at 1:45 PM, Tom Davie  wrote:
>
> On 25 Apr 2013, at 11:40, Diederik Meijer | Ten Horses 
>  wrote:
>
>> I don't agree, blocks are very powerful.
>>
>> I am using Xcode 4.6 and in a project that uses ARC it was throwing warnings 
>> when a block reference to a property caused a retain cycle. This is how I 
>> found it and why I mentioned it in another thread in the first place.
>>
>> I haven't tested it extensively, but it looks as if the compiler recognises 
>> these situations easily and then tells you about it.
>>
>> So I wouldn't call blocks dangerous at all…
>
> You're right – the compiler *is* detecting some simple cases, as I suggested! 
>  Note – this does not make throwing blocks around without paying attention to 
> retain cycles inherently safe though, the compiler can not statically infer 
> all potential cycles.
>
> Thanks
>
> Tom Davie

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: ^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov
Tom, I disagree, because unlike other objects with strong refs, or say
@property(retain), the strong refs in blocks are created implicitly
and it's just too easy to let them slip out of attention. There is no
direct command to create the strong ref, unlike @property(retain). All
you do is *mention* self or even an ivar, and voila, you're done.

I wish there was a safe and elegant solution to this, like we did with
proxy for NSTimer.



On Thu, Apr 25, 2013 at 11:28 AM, Tom Davie  wrote:
>
> On 25 Apr 2013, at 09:20, Oleg Krupnov  wrote:
>
>> Blocks in Obj-C seem convenient and powerful but in fact they are very
>> dangerous because they retain all objects referenced from the block
>> and thereby can implicitly create circular references.
>>
>> If you are not vigilant about every object you mention in the block,
>> you can create one, two or more cycles of circular references causing
>> your objects to never be freed afterwards.
>>
>> This breaks encapsulation of objects with block properties (e.g.
>> MyAnimation.completionBlock) and forces the users of such objects to
>> always keep in mind what they can, and what the cannot write in the
>> block body, and still they can shoot themselves in the feet at any
>> moment by losing vigilance.
>>
>> It seems to me that it's much better to drop the convenience of blocks
>> in favor of safety and full control of retain/assign relationships
>> between my objects.
>>
>> This is a shocker for me too, but I do not see a good solution to this
>> problem. The solution suggested in Session 712 WWDC 2012 is ugly -
>> call some kind of "cancel" method for every block when it's no longer
>> needed. Even with ARC, declaring a weak ref to self and then strong
>> ref to weak ref inside the block is ugly too - you have to add this
>> crap to each and every block you write.
>
> Your argument can equally well be applied to any object that keeps strong 
> references to other objects.  It's not blocks that are doing any of the 
> above, it's reference counting.  And we know that the issues are there – we 
> just choose to have them because the issues with the less leaky solutions are 
> even more severe (especially in C like languages).
>
> Thanks
>
> Tom Davie

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

^Block statement considered harmful for callbacks?

2013-04-25 Thread Oleg Krupnov
Blocks in Obj-C seem convenient and powerful but in fact they are very
dangerous because they retain all objects referenced from the block
and thereby can implicitly create circular references.

If you are not vigilant about every object you mention in the block,
you can create one, two or more cycles of circular references causing
your objects to never be freed afterwards.

This breaks encapsulation of objects with block properties (e.g.
MyAnimation.completionBlock) and forces the users of such objects to
always keep in mind what they can, and what the cannot write in the
block body, and still they can shoot themselves in the feet at any
moment by losing vigilance.

It seems to me that it's much better to drop the convenience of blocks
in favor of safety and full control of retain/assign relationships
between my objects.

This is a shocker for me too, but I do not see a good solution to this
problem. The solution suggested in Session 712 WWDC 2012 is ugly -
call some kind of "cancel" method for every block when it's no longer
needed. Even with ARC, declaring a weak ref to self and then strong
ref to weak ref inside the block is ugly too - you have to add this
crap to each and every block you write.

Thoughts?
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Circular references caused by scheduled NSTimers?

2013-04-19 Thread Oleg Krupnov
> 2) make a __weak reference to self, and only use that inside the block, your 
> controller won't be retained.

That's another alarming problem that I have become aware of in context
of my question. It turns out that if you use blocks instead of
delegates inaccurately, you can end up
creating a strong reference (e.g. by mentioning self in the block) and
a circular reference even without being aware of it. I am now
seriously thinking that blocks can be evil for replacing delegates
(which by convention are always assign properties, i.e. weak
references). Am I right?



On Fri, Apr 19, 2013 at 10:10 AM, Charles Srstka
 wrote:
> On Apr 19, 2013, at 1:01 AM, Oleg Krupnov  wrote:
>
>> I recently encountered an alarming problem that I have never been
>> aware of, and I'd like to ask about the best practice to handle it.
>>
>> Is it true that any object (let's call it Controller) that owns an
>> NSTimer, scheduled to fire a method (let's call it -timerDidFire) of
>> the same Controller, creates a circular reference and causes the
>> Controller to never be released and the timer never stop triggering?
>>
>> It looks like scheduling the timer causes the run loop to retain a
>> reference to the object that implements -timerDidFire, in this case
>> it's the Controller. Is this true? Then this is a circular reference,
>> right?
>>
>> In this case, if [_timer invalidate]; is called only in Controller's
>> dealloc, then the timer never stops firing?
>>
>> Which is the best way to prevent this problem? Currently I'm thinking
>> about some kind of -[controller disconnect]; method that I need to
>> call before [controller release]; in controller's parent object, but
>> that seems a bit unwieldy solution.
>>
>> Any other ideas/considerations? Thanks!
>
> What I'd probably do would be to use a GCD timer instead of an NSTimer. That 
> way, you can pass the timer a block instead of a reference to the controller, 
> and as long as you either 1) don't reference self within the block or 2) make 
> a __weak reference to self, and only use that inside the block, your 
> controller won't be retained.
>
> Charles
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Circular references caused by scheduled NSTimers?

2013-04-19 Thread Oleg Krupnov
Thanks for your answers!

Now I'm thinking that I'd rather create a helper category on NSTimer
with a method that will schedule a timer but under the hood also
create the helper object. In this way, the current code of my project
will almost not change (only change the scheduling method). The helper
class will be private. The helper will not be retained by anyone
except the run loop and will be dealloced immediately after the timer
is invalidated

@interface TimerHelper
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;
- (void)timerDidFire;
@end

@implementation TimerHelper
- (void)timerDidFire
{
  [_target performSelector:_action withObject:nil];
}
@end

@implementation NSTimer (Helper)

+ (NSTimer*)scheduleTimerWithInterval:(NSTimeInterval)interval
target:(id)target action:(SEL)action
{
   TimerHelper* helper = [[[TimerHelper alloc] init] autorelease];
   helper.target = target;
   helper.action = action;
NSTimer* timer =  [NSTimer scheduledTimerWithTimeInterval:interval
target:helper selector:@selector(timerDidFire) userInfo:nil
repeats:YES];
   return timer;
}

@end

@implementation Controller
{
   NSTimer* _timer;
}

- (void)someMethod
{
  _timer = [[NSTimer scheduleTimerWithInterval:interval target:self
action:@selector(someTimerDidFire)] retain];
}

- (void)dealloc
{
   [_timer invalidate];
   [_timer release];
   [super dealloc];
}

@end

I think this is a more elegant solution than public helper. Any caveats?

On Fri, Apr 19, 2013 at 9:53 AM, Graham Cox  wrote:
>
> On 19/04/2013, at 4:35 PM, Greg Parker  wrote:
>
>> Another solution is to introduce a weak reference between the timer and your 
>> controller. Create a helper class that holds a weak reference to your 
>> Controller object.
>
>
> Since Greg and I have offered the same solution, here's an implementation of 
> it you could use:
>
> Usage would be for your controller to alloc/init the helper/proxy (or use the 
> convenience method and retain it) and then in its -dealloc method call 
> -invalidate followed by -release.
>
> // .h file:
>
>
> #import 
>
>
>
> @interface GCTimerTarget : NSObject
> {
> @private
> NSTimer*mTimerRef;
> id  mTrueTargetRef;
> SEL mSelector;
> }
>
> @property (nonatomic, assign) NSTimer*  timer;
> @property (nonatomic, assign) idtrueTarget;
> @property (nonatomic, assign) SEL   selector;
>
> + (GCTimerTarget*)  scheduledTimerWithInterval:(NSTimeInterval) t 
> target:(id) target selector:(SEL) selector repeats:(BOOL) repeats;
>
> - (id)  initForTarget:(id) trueTarget selector:(SEL) selector;
> - (void)invalidate;
>
> @end
>
>
> /// .m file:
>
> #import "GCTimerTarget.h"
>
>
>
> @interface GCTimerTarget ()
>
> - (void)timerCallback:(NSTimer*) timer;
>
> @end
>
>
> #pragma mark -
>
>
> @implementation GCTimerTarget
>
> @synthesize timer = mTimerRef;
> @synthesize trueTarget = mTrueTargetRef;
> @synthesize selector = mSelector;
>
>
>
> + (GCTimerTarget*)  scheduledTimerWithInterval:(NSTimeInterval) t 
> target:(id) target selector:(SEL) selector repeats:(BOOL) repeats
> {
> // convenience method makes the proxy and adds a scheduled timer to 
> it. This can be used instead of the equivalent NSTimer class method
>
> GCTimerTarget* tt = [[[self alloc] initForTarget:target 
> selector:selector] autorelease];
> tt.timer = [NSTimer scheduledTimerWithTimeInterval:t target:tt 
> selector:@selector(timerCallback:) userInfo:nil repeats:repeats];
>
> return tt;
> }
>
>
>
> - (id)  initForTarget:(id) trueTarget selector:(SEL) selector
> {
> self = [super init];
> if( self )
> {
> mTrueTargetRef = trueTarget;
> mSelector = selector;
> }
>
> return self;
> }
>
>
> - (void)invalidate
> {
> self.trueTarget = nil;
> [self.timer invalidate];
> self.timer = nil;
>
> // could call [self autorelease] here to make the proxy a one-line 
> teardown, but it's probably safer to leave it as is
> // and rely on a deliberate -release as usual.
> }
>
>
> - (void)timerCallback:(NSTimer*) timer
> {
> if([self.trueTarget respondsToSelector:self.selector])
> [self.trueTarget performSelector:self.selector 
> withObject:timer];
> }
>
>
> @end
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Circular references caused by scheduled NSTimers?

2013-04-18 Thread Oleg Krupnov
I recently encountered an alarming problem that I have never been
aware of, and I'd like to ask about the best practice to handle it.

Is it true that any object (let's call it Controller) that owns an
NSTimer, scheduled to fire a method (let's call it -timerDidFire) of
the same Controller, creates a circular reference and causes the
Controller to never be released and the timer never stop triggering?

It looks like scheduling the timer causes the run loop to retain a
reference to the object that implements -timerDidFire, in this case
it's the Controller. Is this true? Then this is a circular reference,
right?

In this case, if [_timer invalidate]; is called only in Controller's
dealloc, then the timer never stops firing?

Which is the best way to prevent this problem? Currently I'm thinking
about some kind of -[controller disconnect]; method that I need to
call before [controller release]; in controller's parent object, but
that seems a bit unwieldy solution.

Any other ideas/considerations? Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: CoreAnimation: rendering error 506

2013-03-24 Thread Oleg Krupnov
All right, then what is "Invalid Framebuffer"? What kind of (mis)use of Core 
Animation *might* produce this error? Too large layers? Zero sized layers? Some 
combination of layer properties?

I've made some experiments trying to isolate the problem, and it seems that it 
happens to layers whose content is drawn via delegate, namely after calling 
setNeedsDisplay on a layer, if its delegate implements drawLayer:inContext:, 
even if this method is empty. If I comment out that method entirely, i.e. make 
it non-implemented, the problem disappears. Does it ring something? 


On Mar 24, 2013, at 10:58 PM, David Duncan  wrote:

> On Mar 24, 2013, at 1:17 PM, Oleg Krupnov  wrote:
> 
>> No, only Core Animation with simple CALayers. 
>> 
>> Can it be indicative of some problems in my code, or should I just ignore 
>> it? Everything seems to work fine otherwise. The messages are quite annoying 
>> though. Besides, it seems that in previous version of my app the messages 
>> did not appear, or maybe I did not notice them. It's now hard to tell what 
>> change caused them to appear - there have been too many changes since that 
>> time. Maybe it's even some changes in the OS, it's hard to tell. 
> 
> I'm not certain, but if you can reproduce it consistently I would file a bug.
> 
>> Is there a way to put a breakpoint or otherwise track the cause of the 
>> problem?
> 
> I don't think so. The problem is that the error happened a fair amount of 
> time before the error is actually reported, so the only information available 
> is that an error occurred, not where it happened.
> 
>> 
>> On Mar 24, 2013, at 9:59 PM, David Duncan  wrote:
>> 
>>> On Mar 23, 2013, at 5:00 AM, Oleg Krupnov  wrote:
>>> 
>>>> I get many repetitive messages in the console: "CoreAnimation: rendering 
>>>> error 506"
>>> 
>>> This is a GL error, in this case Invalid Framebuffer.
>>> 
>>> Does your application use OpenGL or a CAOpenGLLayer?
>>> --
>>> David Duncan
>>> 
> 
> --
> David Duncan
> 

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: CoreAnimation: rendering error 506

2013-03-24 Thread Oleg Krupnov
No, only Core Animation with simple CALayers. 

Can it be indicative of some problems in my code, or should I just ignore it? 
Everything seems to work fine otherwise. The messages are quite annoying 
though. Besides, it seems that in previous version of my app the messages did 
not appear, or maybe I did not notice them. It's now hard to tell what change 
caused them to appear - there have been too many changes since that time. Maybe 
it's even some changes in the OS, it's hard to tell. 

Is there a way to put a breakpoint or otherwise track the cause of the problem?

On Mar 24, 2013, at 9:59 PM, David Duncan  wrote:

> On Mar 23, 2013, at 5:00 AM, Oleg Krupnov  wrote:
> 
>> I get many repetitive messages in the console: "CoreAnimation: rendering 
>> error 506"
> 
> This is a GL error, in this case Invalid Framebuffer.
> 
> Does your application use OpenGL or a CAOpenGLLayer?
> --
> David Duncan
> 

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


CoreAnimation: rendering error 506

2013-03-23 Thread Oleg Krupnov
I get many repetitive messages in the console: "CoreAnimation:
rendering error 506"

It disappears when I turn off creating any child layers in my
layer-hosting views.

What could it be caused by?

Can I somehow insert a breakpoint to catch where this output is made?
I tried symbolic breakpoints on write, writev, pwrite, printf,
fprintf, NSLog, NSLogv, asl_log, asl_logv, ask_send, but neither is
fired.

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Callbacks from async blocks

2013-03-16 Thread Oleg Krupnov
Thanks, Roland.

I can see you are comparing the member variable currentOperation of
the caller's class and a locally declared variable
currentOperationAtQueueTime. Good idea. Obviously, the block retains
"self" of the caller object and all local variables referenced from
within the block. So when I call currentOperation I actually get
self->currentOperation, which may change, and
currentOperationAtQueueTime which is frozen. This makes the check
possible

> operation.completionBlock = [ [ SomeMagicBlockObject alloc ]
> initWithPrecompiledCode:(code)code environmentVar1:(id)var1
> environmentVar2:(id)var2 .. ];

Yes, it helps to understand blocks better. A block indeed consists of
a piece of code (like a function pointer) and all retained/copied
variables of the context. Basically, the definition of what an object
is in OOP.

On Sat, Mar 16, 2013 at 3:14 PM, Roland King  wrote:
>
> However, when I use completion blocks instead of delegates, things get
> somewhat vague.
>
> Is it still necessary to store the current operation in a property, or
> does each operation get its own independent copy of the completion
> block, together with its current context? What happens if I create
> another operation and launch it with its completion block - will the
> first operation still fire the block when it's done? If so, how do I
>
>
> Yes it still fires.
>
> correctly discard such call from a ditched operation? I tried to save
> the current operation in a property, but then in the completion block,
> I don't have anything to compare it with, as the completion block
> doesn't provide a sender. Or should I always use blocks with sender as
> a parameter?
>
>
> if you want to do this you probably have to think about it the other way
> around. Imagine in your class
> which fires these things off you have a simple counter member variable,
> 'currentOperation'. It's set to
> 0 when you have no operation and you increment it each time you make a new
> one. The code looks
> like this (typed in mail)
>
>
> currentOperation++;
> NSUInteger currentOperationAtQueueTime = currentOperation;
>
> [ methods which enqueues:^{
>
> // your block work here
>
> // then jump back to the main queue to call operationDidFinish:
> dispatch_async( dispatch_get_main_queue() )
> {
> if( currentOperation == currentOperationAtQueueTime )
> {
> [ yourClass operationDidFinish ];
> currentOperation = 0;
> }
> }
> } ]
>
> Here's the code *in the block* which is checking whether its captured
> version of
> currentOperation is the same as the current, currentOperation, if it is then
> it executes
> the callback and resets the currentOperation. If not, just just does
> nothing. The checking code
> you want now goes in the block, not in the operationDidFinish. Note the two
> ways of
> capturing currentOperation, the first gets the current value out of it and
> captures that,
> that's currentOperationAtQueueTime, the second is using currentOperation in
> the block
> which is equivalent to self->currentOperation, ie it's the value at the time
> that completion
> block runs. That's why it can compare them and know whether to run or not.
>
>
> P.S. It seems that I don't quite understand the nature of blocks. On
> one hand, they are objects, i.e. instances of some class, but on the
> other hand they appear like pieces of code, so they are classes. When
> I write something like operation.completionBlock = ^(){ // some code};
> do I create another instance of a block object or am I reusing the
> same instance over and over again? Is such writing equivalent to a
> object literal, like @"string" for strings? What is even more unclear,
> what happens to the context of blocks, i.e. self and ivars of the
> object where the block is declared, will that be the same retained
> object in all operation instances' completion blocks? How about local
> vars declared outside and used inside of the block - will they be
> different or the same instances for each operation?
>
>
> I'm not sure thinking about them as objects or classes helps. They are
> 'objects' as
> far as they can be retained and released and ARC can manage them, I'd not go
> further
> than that.
>
> The way I sometimes think about blocks to answer the second part of the
> question is that I consider
> the ^{ .. } denotes the time that the block's arguments are captured and
> bound to the code
> which was pre-compiled. So
>
> operation.completionBlock = ^{..};
>
> makes a new block with the same code and the current freeze-dried
> environment. Every time you call
>
> operation.completionBlock();
>
> you will run that same code with the same captured environment until the
> point you do
>
> operation.completionBlock = ^{ .. };
>
> again at which point you'll capture the current environment again at the
> point in your code that line
> is executed. If you assign that block to something like this
>
> anotherOperation.completionBlock = operation.completionBlock;
>
> you really copy the block with its environment as it 

Callbacks from async blocks

2013-03-16 Thread Oleg Krupnov
I want to switch to blocks instead of delegates for small callbacks,
e.g. operationDidFinish or animationDidFinish, but there is a question
I cannot understand.

There is the typical scenario when I need to run an operation (usually
in another thread) and while it is running, I should ignore new
requests to start another such operation. Also, I need to accept
delegate calls (back into the main thread) only from the current
operation, i.e. if I have already ditched an operation that was still
running, I should ignore its delegate call when it completes.

With delegates, I simply save the current operation in a caller's
property when the operation starts, and reset it in delegate method
operationDidFinish:. So when the new request is coming, I check if the
current operation is nil, and only then create a new operation. In the
operationDidFinish: method, i check if the current operation is equal
to the sender, and only then respond with an action.

However, when I use completion blocks instead of delegates, things get
somewhat vague.

Is it still necessary to store the current operation in a property, or
does each operation get its own independent copy of the completion
block, together with its current context? What happens if I create
another operation and launch it with its completion block - will the
first operation still fire the block when it's done? If so, how do I
correctly discard such call from a ditched operation? I tried to save
the current operation in a property, but then in the completion block,
I don't have anything to compare it with, as the completion block
doesn't provide a sender. Or should I always use blocks with sender as
a parameter?

This looks like a common problem, what is the standard solution?

P.S. It seems that I don't quite understand the nature of blocks. On
one hand, they are objects, i.e. instances of some class, but on the
other hand they appear like pieces of code, so they are classes. When
I write something like operation.completionBlock = ^(){ // some code};
do I create another instance of a block object or am I reusing the
same instance over and over again? Is such writing equivalent to a
object literal, like @"string" for strings? What is even more unclear,
what happens to the context of blocks, i.e. self and ivars of the
object where the block is declared, will that be the same retained
object in all operation instances' completion blocks? How about local
vars declared outside and used inside of the block - will they be
different or the same instances for each operation?

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Focus ring and layer-backed views

2013-03-04 Thread Oleg Krupnov
Thanks Kyle,

This is almost perfectly what I need!

However, one problem I've found is with custom layer-hosting controls.
Suppose my control consists of two segments. Each segment is
represented with a child CALayer. Now I want the focus ring to contour
only one segment. In this case, the ring appears below the child
CALayer. In other words, the focus ring is only visible on the
background layer and outside of the control, but appears obscured by
child CALayers. Is there any workaround to make it on top of all
layers?

On Fri, Mar 1, 2013 at 6:33 PM, Kyle Sluder  wrote:
> On Mar 1, 2013, at 1:26 AM, Oleg Krupnov  wrote:
>
>>
>> It seems like a known problem. Is there some workaround?
>
> This is why Apple added the -drawFocusRingMask API. Try using that instead of 
> drawing the focus ring manually.
>
> --Kyle Sluder
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Focus ring and layer-backed views

2013-03-01 Thread Oleg Krupnov
I have two custom views in a container view. The first view is a
custom layer-hosting view, the second one is an ordinary custom view
without layers.

Both views can have keyboard focus and draw focus rings around
themselves. As usual, the focus ring is drawn partially on the
superview.

In the first view, I have a CALayer stretching a bit beyond around the
frame of the view so that it can display the focus ring. The second
view simply calls NSSetFocusRingStyle() and relies on Cocoa for
drawing on the superview.

Now I have a problem that the focus ring gets clipped by the view
frame in either of two cases.

If the container view is not layer-based (wantsLayer == NO), then the
first view's focus ring gets clipped, but the second view's focus ring
is fine. Else if the container view is layer-based (wantsLayer ==
YES), then the first view's focus ring is fine, but the second's is
clipped.

It seems like a known problem. Is there some workaround?

Thanks,
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: CALayer's backgrounds filters having effect only on immediate parent?

2013-02-20 Thread Oleg Krupnov
Not exactly. Here is what the documentation says:

backgroundFilters

An array of Core Image filters to apply to the content immediately
behind the layer. Animatable.

@property(copy) NSArray *backgroundFilters

Discussion
Background filters affect the content behind the layer that shows
through into the layer itself. Typically this content belongs to the
superlayer that acts as the parent of the layer. These filters do not
affect the content of the layer itself, including the layer’s
background color and border. They also do not affect content outside
of the layer’s bounds.

So basically it can blur/filter other layers. So my question remains -
why doesn't it filter all layers below it, but only the immediate
parent layer?

What seems suspicious about it is that the internets are not full of
bitching about this gaping shortcoming, the search yields nothing,
which makes me think that it must be working perfectly for everyone
else, and I'm just missing something obvious.

Any help please?

On Wed, Feb 20, 2013 at 1:51 AM, Graham Cox  wrote:
>
> On 20/02/2013, at 5:42 AM, Oleg Krupnov  wrote:
>
> In my understanding, if I apply, say, a blur filter to layer's
> background (CALayer->backgroundFilters), all layers that are behind
> that layer - that is, immediate parent, grand parent, etc. and all
> children and siblings of those parent and grandparents that are lower
> in the tree of layers - should appear blurred.
>
> An experiment however shows that it's not the case. The background
> blur filter only blurs the direct parent of the target layer, but not
> its grandparent and other layers.
>
> The same applies for compositingFilter.
>
> Am I doing something wrong?
>
> Or, if this is the way it should work as documented, how do achieve
> the effect I want?
>
>
>
> I think your understanding is incorrect. My interpretation of the docs is
> simply that the background - that is to say, the background colour of the
> layer - is filtered. If you think about how layers are composited, this is
> the only interpretation that makes sense - how could a layer retroactively
> apply a bunch of filters to things that have already been rendered?
>
> Setting the filters on the root layer or on some layer further up the tree
> should achieve the effect you want, though most likely you'll want the
> compositingFilters rather than the background filters property.
>
>
> --Graham
>
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

CALayer's backgrounds filters having effect only on immediate parent?

2013-02-19 Thread Oleg Krupnov
In my understanding, if I apply, say, a blur filter to layer's
background (CALayer->backgroundFilters), all layers that are behind
that layer - that is, immediate parent, grand parent, etc. and all
children and siblings of those parent and grandparents that are lower
in the tree of layers - should appear blurred.

An experiment however shows that it's not the case. The background
blur filter only blurs the direct parent of the target layer, but not
its grandparent and other layers.

The same applies for compositingFilter.

Am I doing something wrong?

Or, if this is the way it should work as documented, how do achieve
the effect I want?

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Help me fix a bug: endless recursion in NSTextView?

2013-02-08 Thread Oleg Krupnov
Here we go:

[textView isVerticallyResizable] == YES
[textView isHorizontallyResizable] == NO
[[textView textContainer] heightTracksTextView] == NO
[[textView textContainer] widthTracksTextView] == YES

Does it mean something?

> I'm not sure.  It may have something to do with Retina displays. I would 
> guess that the OS is generating a display configuration change notification 
> when it wakes, which is causing the view to refresh its layout.  You may be 
> able to reproduce the problem if you manually change the display 
> configuration on another, otherwise-unaffected system.

Interesting idea! This could explain at least why only MacBooks are
affected. But I tried Retina resolution emulation on my iMac, and the
bug didn't reproduce… Is this the experiment that you mean?

Could there be some other experiments that I can ask the user to
perform on his MacBook when the bug occasionally reproduces again?

Thanks!

On Fri, Feb 8, 2013 at 9:19 PM, Ken Thomases  wrote:
> Hi,
>
> On Feb 8, 2013, at 12:45 PM, Oleg Krupnov wrote:
>
>> Thanks! This information sounds relevant, but I'm still puzzled. All I
>> do is just use a NSTextView on a window. The text view is resizable by
>> width and height, i.e. the text is wrapped when I change the view's
>> width, and scroll bar appears when I change its height. All pretty
>> standard. I do not delve under the hood, do not assemble my own text
>> editor from the components of the text system. I don't use text
>> container directly in my code.
>
> I'm not sure what's going on.  You should check the following:
>
> [textView isVerticallyResizable]
> [textView isHorizontallyResizable]
> [[textView textContainer] heightTracksTextView]
> [[textView textContainer] widthTracksTextView]
>
>
>> Besides, even if this was the reason, why does it not manifest in
>> normal use cases, but only in some very rare and obscure
>> circumstances? Namely, when MacBook wakes from sleep mode? There were
>> no reports even from iMacs or MacMinis, only MacBooks. Mostly it
>> happens on 10.8.2, but one report was assumably from 10.7.5.
>
> I'm not sure.  It may have something to do with Retina displays.  I would 
> guess that the OS is generating a display configuration change notification 
> when it wakes, which is causing the view to refresh its layout.  You may be 
> able to reproduce the problem if you manually change the display 
> configuration on another, otherwise-unaffected system.
>
> Regards,
> Ken
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Help me fix a bug: endless recursion in NSTextView?

2013-02-08 Thread Oleg Krupnov
Hi Ken,

Thanks! This information sounds relevant, but I'm still puzzled. All I
do is just use a NSTextView on a window. The text view is resizable by
width and height, i.e. the text is wrapped when I change the view's
width, and scroll bar appears when I change its height. All pretty
standard. I do not delve under the hood, do not assemble my own text
editor from the components of the text system. I don't use text
container directly in my code.

Besides, even if this was the reason, why does it not manifest in
normal use cases, but only in some very rare and obscure
circumstances? Namely, when MacBook wakes from sleep mode? There were
no reports even from iMacs or MacMinis, only MacBooks. Mostly it
happens on 10.8.2, but one report was assumably from 10.7.5.

I appreciate your help very much! I've found nothing in the Internet
on this, and the bug is pretty critical.


On Fri, Feb 8, 2013 at 5:11 PM, Ken Thomases  wrote:
> On Feb 8, 2013, at 5:05 AM, Oleg Krupnov wrote:
>
>> I've received a few reports from users that my app hangs and consumes
>> 100% CPU, and they have to force quit it. It usually happens on
>> MacBooks after they are awaken from sleep mode.
>>
>> One user also sent the following crash report:
>>
>> 16  com.apple.CoreFoundation0x7fff8846547a
>> _CFXNotificationPost + 2554
>> 17  com.apple.Foundation0x7fff85251846
>> -[NSNotificationCenter postNotificationName:object:userInfo:] + 64
>> 18  com.apple.AppKit0x7fff8cb8821e -[NSView
>> _postFrameChangeNotification] + 259
>> 19  com.apple.AppKit0x7fff8cb728f3 -[NSView
>> setFrameSize:] + 1352
>> 20  com.apple.AppKit0x7fff8cc47c86
>> -[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
>> 21  com.apple.AppKit0x7fff8cc13d33
>> -[NSTextContainer setContainerSize:] + 193
>> 22  com.apple.AppKit0x7fff8cc43ac9
>> -[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289
>> 23  com.apple.CoreFoundation0x7fff8846547a
>> _CFXNotificationPost + 2554
>> 24  com.apple.Foundation0x7fff85251846
>> -[NSNotificationCenter postNotificationName:object:userInfo:] + 64
>> 25  com.apple.AppKit0x7fff8cb8821e -[NSView
>> _postFrameChangeNotification] + 259
>> 26  com.apple.AppKit0x7fff8cb728f3 -[NSView
>> setFrameSize:] + 1352
>> 27  com.apple.AppKit0x7fff8cc47c86
>> -[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
>> 28  com.apple.AppKit0x7fff8cc13d33
>> -[NSTextContainer setContainerSize:] + 193
>> 29  com.apple.AppKit0x7fff8cc43ac9
>> -[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289
>
> I just responded to an identical post in the dev forums, which I assume was 
> yours <https://devforums.apple.com/message/783296#783296>:
>
> See the last paragraph from Text System Storage Layer Overview: Tracking the 
> Size of a Text View:
> https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextStorageLayer/Tasks/TrackingSize.html
>
>> Note that a text view can be resized based on its text container, and a text 
>> container can resize itself based on its text view. If you set both objects 
>> up to resize automatically in the same dimension, your application can get 
>> trapped in an infinite loop. When text is added to the text container, the 
>> text view is resized to fit the area actually used for text; this causes the 
>> text container to resize itself and relay its text, which causes the text 
>> view to resize itself again, and so on ad infinitum. Each type of size 
>> tracking has its proper uses; be sure to use only one for either dimension.
>
> Cheers,
> Ken
>

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Help me fix a bug: endless recursion in NSTextView?

2013-02-08 Thread Oleg Krupnov
Hi,

I've received a few reports from users that my app hangs and consumes
100% CPU, and they have to force quit it. It usually happens on
MacBooks after they are awaken from sleep mode.

One user also sent the following crash report:

16  com.apple.CoreFoundation0x7fff8846547a
_CFXNotificationPost + 2554
17  com.apple.Foundation0x7fff85251846
-[NSNotificationCenter postNotificationName:object:userInfo:] + 64
18  com.apple.AppKit0x7fff8cb8821e -[NSView
_postFrameChangeNotification] + 259
19  com.apple.AppKit0x7fff8cb728f3 -[NSView
setFrameSize:] + 1352
20  com.apple.AppKit0x7fff8cc47c86
-[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
21  com.apple.AppKit0x7fff8cc13d33
-[NSTextContainer setContainerSize:] + 193
22  com.apple.AppKit0x7fff8cc43ac9
-[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289
23  com.apple.CoreFoundation0x7fff8846547a
_CFXNotificationPost + 2554
24  com.apple.Foundation0x7fff85251846
-[NSNotificationCenter postNotificationName:object:userInfo:] + 64
25  com.apple.AppKit0x7fff8cb8821e -[NSView
_postFrameChangeNotification] + 259
26  com.apple.AppKit0x7fff8cb728f3 -[NSView
setFrameSize:] + 1352
27  com.apple.AppKit0x7fff8cc47c86
-[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
28  com.apple.AppKit0x7fff8cc13d33
-[NSTextContainer setContainerSize:] + 193
29  com.apple.AppKit0x7fff8cc43ac9
-[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289

These few strings repeat forever, like if there was an endless
recursion. Finally, it ends with what looks like a stack overflow:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_PROTECTION_FAILURE at 0x7fff57272d80

VM Regions Near 0x7fff57272d80:
MALLOC_SMALL   7fc06500-7fc06700 [ 32.0M]
rw-/rwx SM=PRV
-- STACK GUARD7fff53a73000-7fff57273000 [ 56.0M]
---/rwx SM=NUL  stack guard for thread 0
Stack  7fff57273000-7fff57a73000 [ 8192K]
rw-/rwx SM=COW  thread 0

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.CoreFoundation0x7fff8842e477
_CFArrayReplaceValues + 23
1   com.apple.CoreFoundation0x7fff88470164
CFRunLoopRemoveTimer + 372
2   com.apple.CoreFoundation0x7fff8846ff2f
CFRunLoopTimerInvalidate + 383
3   com.apple.AppKit0x7fff8cca8132
-[NSScrollerImpPair _cancelOverlayScrollerHideTimer] + 45
4   com.apple.AppKit0x7fff8cb2969e
-[NSScrollerImpPair _rescheduleOverlayScrollerHideTimerWithDelay:] +
61
5   com.apple.AppKit0x7fff8cb28ab9
-[NSScrollerImpPair
_updateOverlayScrollersStateWithReason:forceAtLeastKnobsVisible:] +
3325
6   com.apple.AppKit0x7fff8cc4cc95
-[NSClipView _immediateScrollToPoint:] + 467
7   com.apple.AppKit0x7fff8cc4ca12
-[NSClipView scrollToPoint:] + 268
8   com.apple.AppKit0x7fff8cd1557d
-[NSScrollView scrollClipView:toPoint:] + 426
9   com.apple.AppKit0x7fff8cc4c79c
-[NSClipView _scrollTo:animateScroll:flashScrollerKnobs:] + 1626
10  com.apple.AppKit0x7fff8cc4bf60
-[NSClipView _reflectDocumentViewFrameChange] + 127
11  com.apple.AppKit0x7fff8cb881f3 -[NSView
_postFrameChangeNotification] + 216
12  com.apple.AppKit0x7fff8cb728f3 -[NSView
setFrameSize:] + 1352
13  com.apple.AppKit0x7fff8cc47c86
-[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
14  com.apple.AppKit0x7fff8cc13d33
-[NSTextContainer setContainerSize:] + 193
15  com.apple.AppKit0x7fff8cc43ac9
-[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289
16  com.apple.CoreFoundation0x7fff8846547a
_CFXNotificationPost + 2554
17  com.apple.Foundation0x7fff85251846
-[NSNotificationCenter postNotificationName:object:userInfo:] + 64
18  com.apple.AppKit0x7fff8cb8821e -[NSView
_postFrameChangeNotification] + 259
19  com.apple.AppKit0x7fff8cb728f3 -[NSView
setFrameSize:] + 1352
20  com.apple.AppKit0x7fff8cc47c86
-[NSTextView(NSPrivate) _setFrameSize:forceScroll:] + 1367
21  com.apple.AppKit0x7fff8cc13d33
-[NSTextContainer setContainerSize:] + 193
22  com.apple.AppKit0x7fff8cc43ac9
-[NSTextContainer(NSPrivate) _resizeAccordingToTextView:] + 289

The whole crash dump doesn't contain a single line from my own code -
only system libraries. Or maybe it's simply truncated at some point.
Anyway, it's hard 

Excluding a XIB from project depending on configuration

2013-01-21 Thread Oleg Krupnov
I have a XIB file with some debugging & tweaking window which is only
needed in the Debug configuration of my project. I can exclude the
debug code with some #ifdefs, but I would like also to exclude the XIB
from the release build. Is there a way in Xcode to achieve this?

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to get registered dragged types from NSWindow?

2013-01-14 Thread Oleg Krupnov
Unlike NSView, there is no -registeredDraggedTypes method in NSWindow.
How do I find out which dragged types a window is registered to?

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to enable the close window button while showing a modal sheet?

2013-01-08 Thread Oleg Krupnov
I don't want to start a HIG flame on this, but just want to know if
it's technically possible to enable the close button of a window while
showing a modal sheet (NSApp beginSheet:modalForWindow:…) on it?

Thanks!

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

How to check if the app is sandboxed and what entitlements it has got?

2012-10-27 Thread Oleg Krupnov
Hi,

I'm writing a component which I intend to use in several my apps. Some
of the apps may be sandboxed. I'd like to turn off some functionality
in case if the app is sandboxed and there are no entitlements that I
need.

I'd be happy with either compile-time or run-time solution.

I've googled a solution
http://oleb.net/blog/2012/02/checking-code-signing-and-sandboxing-status-in-code/
but it's using a rather obscure Security framework and it doesn't
check particular entitlements. Generally it looks like a hacky
workaround. I wonder if there is a simpler straightforward solution.

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is QuickLook implemented upon CGImage or CGImageSource under the hood?

2012-09-07 Thread Oleg Krupnov
Hi Mike,

Interesting, thanks. I wasn't aware that CGImageSource was the fastest
on the Mac. QuickLook sometimes seems so amazingly fast, even with
giant images, so that it made me think it uses some more advanced or
more low-level technology than CGImageSource which seems pretty old,
isn't it. My question was basically about this.

A corollary: if QuickLook is built on CGImageSource, then QuickLook
should support the same set of image formats as CGImageSource. Is this
the case? (Not counting third-party QL plugins)

I want to load an image as fast as possible and display it. But maybe
I gonna need to manipulate it a bit. What's the story change?

Thanks,


On Fri, Sep 7, 2012 at 3:12 PM, Mike Abdullah  wrote:
> I would be surprised if QuickLook is bothering to use anything lower-level.
> The raw truth of it is that CGImageSource is intended to be the fastest
> image-decoding library on the Mac. Quick Look should have a possible benefit
> in raw speed because it might have already cached a file's thumbnail.
>
> Of course, once you get into image manipulation, the story might change.
> What's your end goal here?
>
>
> On 7 Sep 2012, at 13:02, Oleg Krupnov  wrote:
>
> I guess I should have asked "Is QuickLook implemented upon
> CGImageSource/CGImage or lower-level libraries under the hood?" I
> mean, the question is not I CGImageSource vs. CGImage, but rather
> CGImageSource/CGImage vs. lower-level libraries like libjpeg etc.
>
> I tried to measure the performance of QuickLook vs CGImageSource but
> it's hard to make a clean experiment. I keep getting different figures
> each time. At superficial glance, it seems that they show nearly equal
> performance.
>
> But it would be really curious what libraries QuickLook uses under the hood.
>
> Thanks!
>
> On Fri, Sep 7, 2012 at 2:09 PM, Mike Abdullah 
> wrote:
>
> Your question in the subject makes little sense. CGImageSource is a means to
> create CGImages. Quick Look likely uses both therefore.
>
> Ultimately, you need to test different image loading routes to see which
> suits your needs.
>
> CGImageSourceCreateImageAtIndex
> Generates full-size images as fast as it can
>
> QLThumbnailImageCreate
> Generates thumbnails
> Might have the thumbnail already cached for speed
> Is going to spend a little time in cross-process communication
> Logs warnings if used on the main thread in my experience
> Can handle any file type, not just images
>
> CGImageSourceCreateThumbnailAtIndex
> Generates thumbnails
> Very fast
>
> On 7 Sep 2012, at 10:21, Oleg Krupnov  wrote:
>
> And what is the fastest method for image loading,
> QLThumbnailImageCreate or CGImageSourceCreateImageAtIndex?
>
> Thanks!
> ___
>
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
> https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40mikeabdullah.net
>
> This email sent to cocoa...@mikeabdullah.net
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is QuickLook implemented upon CGImage or CGImageSource under the hood?

2012-09-07 Thread Oleg Krupnov
I guess I should have asked "Is QuickLook implemented upon
CGImageSource/CGImage or lower-level libraries under the hood?" I
mean, the question is not I CGImageSource vs. CGImage, but rather
CGImageSource/CGImage vs. lower-level libraries like libjpeg etc.

I tried to measure the performance of QuickLook vs CGImageSource but
it's hard to make a clean experiment. I keep getting different figures
each time. At superficial glance, it seems that they show nearly equal
performance.

But it would be really curious what libraries QuickLook uses under the hood.

Thanks!

On Fri, Sep 7, 2012 at 2:09 PM, Mike Abdullah  wrote:
> Your question in the subject makes little sense. CGImageSource is a means to
> create CGImages. Quick Look likely uses both therefore.
>
> Ultimately, you need to test different image loading routes to see which
> suits your needs.
>
> CGImageSourceCreateImageAtIndex
> Generates full-size images as fast as it can
>
> QLThumbnailImageCreate
> Generates thumbnails
> Might have the thumbnail already cached for speed
> Is going to spend a little time in cross-process communication
> Logs warnings if used on the main thread in my experience
> Can handle any file type, not just images
>
> CGImageSourceCreateThumbnailAtIndex
> Generates thumbnails
> Very fast
>
> On 7 Sep 2012, at 10:21, Oleg Krupnov  wrote:
>
> And what is the fastest method for image loading,
> QLThumbnailImageCreate or CGImageSourceCreateImageAtIndex?
>
> Thanks!
> ___
>
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
> https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40mikeabdullah.net
>
> This email sent to cocoa...@mikeabdullah.net
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Is QuickLook implemented upon CGImage or CGImageSource under the hood?

2012-09-07 Thread Oleg Krupnov
And what is the fastest method for image loading,
QLThumbnailImageCreate or CGImageSourceCreateImageAtIndex?

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to create multi-resolution NSImage programmatically?

2012-07-20 Thread Oleg Krupnov
Hi,

I need to create NSImages programmatically in memory, and I want them
to display correctly on Retina displays.

Namely, I have two images btnImage.png and btnim...@2x.png in
resources of my app bundle. At run time, I take that image [NSImage
imageNamed:@"btnImage"] and split it into three NSImage slices and
draw them using NSDrawThreePartImage, with respect of the current
resolution (1x or 2x).

I tried to imitate the way NSImage seems to handle multi-res images: I
created an NSImage and two NSBitmapImageRep's in it, corresponding to
the two image reps of the btnImage, and drew each rep respectively
using -[NSGraphicsContext graphicsContextWithBitmapImageRep:] and
[NSImageRep drawInRect:fromRect:operation:fraction:respectFlipped:hints:].

I wonder if this is a valid approach and maybe there is another recommended way?

As I tested it, it doesn't always work correctly. In normal NSViews -
everything is fine. In layer-hosting views when drawn in CALayer via
delegate, the image is chosen correctly (1x or 2x) but the 2x image is
scaled down (sic!) so that it appears twice smaller than it should be.
When I draw the original btnImage image in the same CALayer, it is
selected and scaled properly in both 1x and 2x. I have no idea what is
the problem.

BTW, the only modification I made in my layer-hosting view to support
retina is adding this method to the delegate implementation:

- (BOOL)layer:(CALayer*)layer
shouldInheritContentsScale:(CGFloat)contentsScale
fromWindow:(NSWindow*)window
{
   return YES;
}

Thanks
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Defining subclasses at run time

2012-06-11 Thread Oleg Krupnov
Hi,

I'm solving the following problem. I have a huge array of items of the
same class MyItem. All items need to share a certain global "context"
variable. Normally, I would wrap access to this variable in a
class-level (+) method of MyItem, like +[MyItem getContext].

Now the problem is that I need multiple arrays of MyItems have
different contexts. The solution could be to add the context pointer
as an ivar to each MyItem instance, but I would not like to waste
memory on that (the arrays are huge).

How do I solve this problem?

I have an idea that I could spawn new subclasses of MyClass at run
time, for each new array of MyItems, assigning each class with a
different class-level context variable, and then instantiating items
from that subclass. In this way, +[_runtime_subclass_of_MyItem
getContext] would return a different context value for each array.
This would reuse the "isa" pointer that's already in any NSObject
instance.

Is this possible in Obj-C? Or is there a better idea?

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: [Obj-C] if (self) vs. if (self != nil)

2012-02-24 Thread Oleg Krupnov
Yes, I'm aware that in practice it doesn't matter, but when I code, I have to 
choose one or the other way, anyway. My current choice is (self != nil) for the 
sake of explicitness.

Thanks everyone for an interesting discussion, especially Kyle for such an 
exhaustive reference :)  

P.S. Sorry for posting the question into the wrong list. I'm a bit shaky in the 
classification of apple lists.



On Friday, February 24, 2012 at 9:47 PM, Kyle Sluder wrote:

> On Fri, Feb 24, 2012 at 6:50 AM, Oleg Krupnov  (mailto:oleg.krup...@gmail.com)> wrote:
> > An interesting question. The following samples are equivalent in terms
> > of compiled code, but which one is more correct from the language's
> > point of view?
> >  
> > self = [super init];
> > if (self)
> > {
> > }
> > return self;
> >  
> > self = [super init];
> > if (self != nil)
> > {
> > }
> > return self;
> >  
> > The Xcode samples promote the first variant, but I'm wondering if the
> > second one is more correct?
> >  
> > The "nil" is defined as follows (jumped to definition)
> >  
> > #define nil NULL
> > #define NULL ((void*)0)
> >  
> > So basically, nil is of type "void*", so the expression "self != nil"
> > compares two pointers and the result is "boolean", which is perfect
> > for testing in the "if" statement. But the "self" alone is of type
> > "pointer" and so when it is tested by the "if" statement, it's
> > implicitly cast to the type "boolean".
> >  
> > I also heard that generally speaking NULL is not necessarily always
> > equal to 0 on all architectures.
> >  
>  
>  
> §6.3.2.3 ¶3 defines the null pointer constant as "an integer constant
> expression with the value 0, or such an expression cast to type void
> *". A null pointer is one that has been assigned the value of the null
> pointer constant, or has been assigned the value of another null
> pointer.
>  
> But you are correct that conversion of a null pointer to integer is
> NOT defined to compare equal to an integer expression with a value of
> zero. §6.3.2.3 ¶6 makes that clear: "Any pointer type may be converted
> to an integer type. Except as previously specified, the result is
> implementation-defined." However, footnote 56 states that "The mapping
> functions for converting a pointer to an integer or an integer to a
> pointer are intended to
> be consistent with the addressing structure of the execution environment."
>  
> But I'm not sure the integer conversion is necessarily relevant. The
> semantics of the if statement are defined by §6.8.4.1 ¶2: "the first
> substatement is executed if the expression compares unequal to 0." It
> is left unspecified if '0' is an integer constant expression or an
> arithmetic expression with an integer value of zero. If the former,
> then the pointer is compared against the null pointer constant per
> §6.3.2.3 ¶4. If the latter, the pointer is converted to integer per
> implementation-defined behavior and the comparison is performed, which
> might itself result in undefined behavior per §6.5 ¶5 since the
> conversion is not guaranteed to produce a value within range of any
> integer type.
>  
> In practice, it's a moot point since on all architectures that Apple's
> Objective-C runtime runs on use identical bit patterns for null
> pointers as they do for integer zero.
>  
> But absent any information I'm unaware of, the explicit comparison is
> "more correct" in the sense that it doesn't leave any room for
> implementation-defined behavior.
>  
> --Kyle Sluder  

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

[Obj-C] if (self) vs. if (self != nil)

2012-02-24 Thread Oleg Krupnov
An interesting question. The following samples are equivalent in terms
of compiled code, but which one is more correct from the language's
point of view?

self = [super init];
if (self)
{
}
return self;

self = [super init];
if (self != nil)
{
}
return self;

The Xcode samples promote the first variant, but I'm wondering if the
second one is more correct?

The "nil" is defined as follows (jumped to definition)

#define nil NULL
#define NULL ((void*)0)

So basically, nil is of type "void*", so the expression "self != nil"
compares two pointers and the result is "boolean", which is perfect
for testing in the "if" statement. But the "self" alone is of type
"pointer" and so when it is tested by the "if" statement, it's
implicitly cast to the type "boolean".

I also heard that generally speaking NULL is not necessarily always
equal to 0 on all architectures.

Thoughts?
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Querying system-wide base for file size calculation (base-2 vs base-10)

2011-11-23 Thread Oleg Krupnov
Yes, I checked the source code of switchDiskSizeBase, and as far as I
can see, the guy is using some low-level hack, like opening a system
framework binary, uncompress it, find some bytes at certain magic
offset, read and rewrite them. This kind of thing isn't acceptable for
my app, I'm looking for some legitimate ways, some public APIs.



On Wed, Nov 23, 2011 at 9:31 PM, Jens Alfke  wrote:
>
>
> Have you downloaded switchDiskSizeBase and looked at the source code to see 
> how it works? Maybe when you see what it changes it’ll be clear how to read 
> the same value back in your app.
>
> —Jens
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Querying system-wide base for file size calculation (base-2 vs base-10)

2011-11-23 Thread Oleg Krupnov
Hi,

Previously, I've been using a simple switch: use 10-based for 10.6 and
later, and 2-based for earlier versions of the Mac OS X, but I've
learned that there are some utilities (e..g switchDiskSizeBase, see
http://web.me.com/brkirch/brkirchs_Software/switchDiskSizeBase/switchDiskSizeBase.html)
that modify the base system-wide.

So the question is: Is there a system API for querying what base is
currently used system-wide for calculating file sizes?

Thanks
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: How to get mount options of a mounted volume?

2011-10-11 Thread Oleg Krupnov
Hi Ken,

Bingo! The f_flags field of statfs structure. Thanks, Ken.

I've also checked FSMegaInfo, but I haven't found any additional ways
to check the mount flags. It seems to use the same BSD statfs way.

Oleg.

On Wed, Oct 12, 2011 at 5:51 AM, Ken Thomases  wrote:
> On Oct 11, 2011, at 6:42 AM, Oleg Krupnov wrote:
>
>> I'd like to get the mount options of a particular volume (like "rw",
>> "nobrowse", "automounted" etc.) of a mounted volume, like those I get
>> when I run "mount" command in the Terminal.
>
> There are many ways to get volume information.  For the mount flags, you can 
> look at statfs().
>
> It can also be instructive to look at the documentation for the getattrlist() 
> function.  It is basically the swiss army knife of file system APIs.  It's 
> what most of the others are based on.
>
> Apple's FSMegaInfo sample is a good tool for exploring the various APIs for 
> querying file system data, although it's getting a bit long in the tooth now, 
> and is missing some of the newer APIs.
> https://developer.apple.com/library/mac/#samplecode/FSMegaInfo/Introduction/Intro.html
>
> Cheers,
> Ken
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to get mount options of a mounted volume?

2011-10-11 Thread Oleg Krupnov
Hi,

I'd like to get the mount options of a particular volume (like "rw",
"nobrowse", "automounted" etc.) of a mounted volume, like those I get
when I run "mount" command in the Terminal.

It should be easy, but I can't seem to find anything in the library.

Thanks
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: The best way to call Cocoa methods not implemented in previous versions of the SDK?

2011-09-06 Thread Oleg Krupnov
So, gentlemen, the OP has ended up completely baffled with your discussion :)

Do I have to build and ship two separate versions of my app, for 10.6
and for 10.7??! This would be a nightmare!

At the bottom line, what is the legitimate way of supporting older
versions of Mac OS X (10.6) in an app designed for newer ones (10.7)?

This should be an easy and well-known topic, because Mac OS X gets
updated all the time! How can it cause so much discussion at all? Is
there an official recommendation in the docs regarding this question?



On Wed, Sep 7, 2011 at 7:23 AM, Chris Hanson  wrote:
> On Sep 6, 2011, at 8:52 PM, Ken Thomases wrote:
>
>>> And has been discussed in the rest of the thread, you should not leave your 
>>> Base SDK set to an earlier OS and then invoke methods introduced in a later 
>>> OS, because the new methods may require new-OS framework behavior.
>>
>> When did I say anything about invoking methods introduced in a later OS?
>
> This thread is the result of someone trying to take advantage of 10.7 
> features in code that needs to run on 10.6.
>
> If a developer who wants to do that builds against the 10.6 SDK, and invokes 
> new-in-10.7 methods when running on 10.7, they can get incorrect behavior as 
> a result.  That's because the frameworks are allowed to call their own 
> methods too, they're not public-only entry points.
>
> So the new-in-10.7 -bar may invoke -foo, which has different behavior when 
> linked on 10.6 or before, but expect -foo's 10.7 behavior.  Boom, the app is 
> broken.  Don't do that.
>
>>  If one develops an app for, say, 10.7 and has tested/validated it, but has 
>> set their SDK to Latest, then merely building it on the next generation of 
>> the OS/tools _will_ break it.  Without one having made any changes to their 
>> code.
>
> Merely building it with any different tool chain at all — and even a 
> different build of "the same" SDK — invalidates all of your testing and 
> validation as well.  (SDKs can and do change over time too; an SDK is "an 
> artifact that describes the API of an OS version" not "guaranteed to be the 
> exact bits from the headers and libraries of an OS version.")
>
> Since you need to re-test/re-validate any time you switch tools, it should be 
> no more burden to have an updated SDK at the same time any more than it is to 
> have an updated compiler, linker, or IDE.
>
> You don't actually win anything just by preserving the SDK version you're 
> building against. And as I explained above (and others have explained in this 
> thread) you can run into significant compatibility issues when attempting to 
> build for an older SDK but use new-than-that-SDK methods.
>
>>> It is a very strong recommendation that you set your Base SDK to Latest and 
>>> use the Deployment Target to specify the least recent OS on which your 
>>> application will be run.
>>
>> It may be a very strong recommendation, but it isn't a wise one.
>
> You're welcome to think anything you want about it.  Nonetheless, it doesn't 
> change how developers should be building their software for OS X.
>
> It's already how developers are used to building applications for iOS, so it 
> can't be that huge a burden.
>
>  -- Chris
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


The best way to call Cocoa methods not implemented in previous versions of the SDK?

2011-09-06 Thread Oleg Krupnov
Hi,

I'm implementing a new Lion's API, namely the resume. I need to make
the following call:

[window setRestorationClass:someClass];

I'd like my app to also work on Snow Leopard, so I do this:

if ([window respondsToSelector:@selector(setRestorationClass:)])
{
[window setRestorationClass:someClass];
}

however, because I compile for Snow Leopard, the compiler will still
give me a warning that the setRestorationClass: method is not defined.

How do I work around this, other than using [NSObject
performSelector:withObject:...], which looks too cumbersome, and other
than deriving all windows from a base class that will define this
method? Extensions are not suitable either, because there is no way to
call super from them. Any other ideas?

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


When and where to call [NSWindow setRestorationClass]?

2011-09-01 Thread Oleg Krupnov
Hi,

I am implementing the Lion's User Interface Preservation, and must be
overlooking something. The Mac OS X Application Programming Guide
says:

"Every window is expected to identify a class that knows about the
window and can act on its behalf at launch time. This class is known
as the restoration class of the window and its job is to do whatever
is necessary to create the window when asked to do so by Cocoa."

I looked into Interface Builder, but couldn't find it.

There is -[NSWindow setRestorationClass:] method for this, but when
and where should I call it from code?

What is the recommended way of doing this?

Thanks.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Stack trace for exceptions trimmed off on Lion?

2011-08-07 Thread Oleg Krupnov
Hi,

I've occasionally noticed after upgrading to Lion that my exception
handling code no longer provides full stack trace, but only some
trimmed piece.

For example, I performed the following experiment. There is an
-emulateCrash: action method, implemented in MyWindowController,
attached to a menu command. In that method I simply raise and
NSAssert(false, @"Test crash").

Here is the full stack trace I see in the debugger:

0   CoreFoundation  0x7fff93b9d986
__exceptionPreprocess + 198
1   libobjc.A.dylib 0x7fff92623d5e
objc_exception_throw + 43
2   CoreFoundation  0x7fff93b9d7ba
+[NSException raise:format:arguments:] + 106
3   Foundation  0x7fff88df014f
-[NSAssertionHandler
handleFailureInMethod:object:file:lineNumber:description:] + 169
4   MyApp   0x0001000445e6
-[MyWindowController emulateCrash:] + 195
5   CoreFoundation  0x7fff93b8d11d -[NSObject
performSelector:withObject:] + 61
6   AppKit  0x7fff89d71852
-[NSApplication sendAction:to:from:] + 139
7   AppKit  0x7fff89e5e34f
-[NSMenuItem _corePerformAction] + 399
8   AppKit  0x7fff89e5e086
-[NSCarbonMenuImpl performActionWithHighlightingForItemAtIndex:] + 125
9   AppKit  0x7fff8a0f9e9c -[NSMenu
_internalPerformActionForItemAtIndex:] + 38
10  AppKit  0x7fff89f8c3f1
-[NSCarbonMenuImpl _carbonCommandProcessEvent:handlerCallRef:] + 138
11  AppKit  0x7fff89dd80bf
NSSLMMenuEventHandler + 339
12  HIToolbox   0x7fff935478ec
_ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec
+ 1263
13  HIToolbox   0x7fff93546ef8
_ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec
+ 446
14  HIToolbox   0x7fff9355dd03
SendEventToEventTarget + 76
15  HIToolbox   0x7fff935a4249
_ZL18SendHICommandEventjPK9HICommandjjhPKvP20OpaqueEventTargetRefS5_PP14OpaqueEventRef
+ 398
16  HIToolbox   0x7fff9368b0f1
SendMenuCommandWithContextAndModifiers + 56
17  HIToolbox   0x7fff936d15e1
SendMenuItemSelectedEvent + 253
18  HIToolbox   0x7fff9359d32d
_ZL19FinishMenuSelectionP13SelectionDataP10MenuResultS2_ + 101
19  HIToolbox   0x7fff93594a75
_ZL14MenuSelectCoreP8MenuData5PointdjPP13OpaqueMenuRefPt + 600
20  HIToolbox   0x7fff93594034
_HandleMenuSelection2 + 585
21  AppKit  0x7fff89cd7ce1
_NSHandleCarbonMenuEvent + 250
22  AppKit  0x7fff89c6d6c7 
_DPSNextEvent + 1993
23  AppKit  0x7fff89c6ca95
-[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 135
24  AppKit  0x7fff89c693d6
-[NSApplication run] + 463
25  AppKit  0x7fff89ee752a
NSApplicationMain + 867
26  MyApp   0x00011f27 main + 33
27  MyApp   0x00011ee4 start + 52
28  ??? 0x0001 0x0 + 1

However, when I look at -[NSException callStackReturnAddresses]  or
[[exception userInfo] objectForKey:@"NSStackTraceKey"], I only get
this:

0  HIToolbox0x7fff93547910
_ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec()
1  HIToolbox0x7fff93546ef8
_ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec()
2  HIToolbox0x7fff9355dd03 SendEventToEventTarget()
3  HIToolbox0x7fff935a4249
_ZL18SendHICommandEventjPK9HICommandjjhPKvP20OpaqueEventTargetRefS5_PP14OpaqueEventRef()
4  HIToolbox0x7fff9368b0f1 
SendMenuCommandWithContextAndModifiers()
5  HIToolbox0x7fff936d15e1 
SendMenuItemSelectedEvent()
6  HIToolbox0x7fff9359d32d
_ZL19FinishMenuSelectionP13SelectionDataP10MenuResultS2_()
7  HIToolbox0x7fff93594a75
_ZL14MenuSelectCoreP8MenuData5PointdjPP13OpaqueMenuRefPt()  8
HIToolbox   0x7fff93594034 _HandleMenuSelection2()
9 AppKit0x7fff89cd7ce1 
_NSHandleCarbonMenuEvent()
10 AppKit   0x7fff89c6d6c7 _DPSNextEvent()
11 

Automatic warnings for NSLocalizedString?

2011-07-20 Thread Oleg Krupnov
Hi,

Is there a way, at compile time, to automatically check that all
strings referenced anywhere in my project via NSLocalizedString have
their localized counterparts in *.strings files for all localizations
I have included into the project? So that if a string is missing in a
localization, I would receive some kind of warning.

Thanks
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


CIImage directly to CALayer contents?

2011-07-01 Thread Oleg Krupnov
Hi,

I'm a little shaky in this area, so I beg your pardon.

CALayer has a "contents" property which is a CGImageRef, i.e. a Core
Graphic image. CGImages are stored in RAM.

CALayer is built on top of OpenGL and uses VRAM to store its bitmap
image internally (a texture).

Now suppose that I have a CIImage constructed with
+imageWithContentsOfURL. The image is loaded (lazily) directly to
VRAM.

So, If I go the suggested route, and first create a CGImage from
CIImage, then assign it to CALayer's contents, I will effectively copy
the image from VRAM to RAM and then again back to VRAM, which is slow,
memory consuming, and generally unnecessary.

Am I correct?

If so, is there a way to pass a CIImage directly to CALayer without
going beyond VRAM?

Thanks!

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: How to cancel an asynchronous GCD block?

2011-07-01 Thread Oleg Krupnov
>> I am migrating my code to use GCD blocks instead of NSOperations.
>
> Why?

I should have said, I'm writing a new app and I am migrating my
knowledge of implementing multi-threading from NSOperation to GCD :)

(And I should say, I'm beginning to like the easiness of GCD, even
though I was initially reluctant to use blocks, because they seem
harder to read, less encapsulated and easier to make scope mistakes.)

>> But this seems a bit clunky (compared to the elegance of GCD code),
>
> It's pretty much your only option.  GCD doesn't have a notion of canceling a 
> task, so you can only set a flag and check it.

Thanks, now I know.

> If at any point it evaluates to true, then you know somebody has set it or is 
> in the process of setting it, which means it really is supposed to be true.  
> In theory, yes, the code which is setting it may not have completed, but you 
> don't care.

I undersand that, but I just wanted to be a purist :) Well, I will do
as Charles suggested: I will declare the property as atomic and
synthesize it.

Thanks to everyone!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to cancel an asynchronous GCD block?

2011-07-01 Thread Oleg Krupnov
Hi,

I am migrating my code to use GCD blocks instead of NSOperations.

NSOperation has a -cancel method to thread-safely notify the
NSOperation thread that it needs to be canceled.

How do you do this for an async GCD block?

I.e. suppose I have the following code:

@implementation MyClass
- (void)myMethod
{
dispatch_async(
   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
   ^{
do_some_lengthy_cancelable_operation();
   });
}
@end

I need to be able to cancel do_some_lengthy_cancelable_operation() at
some point.

The first solution that comes to my mind is the following.

@interface MyClass 
{
  bool m_isCancelled
}
- (bool)isCancelled;
@end

@implementation MyClass
- (void)myMethod
{
dispatch_async(
   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
   ^{
do_some_lengthy_cancelable_operation(self);
   });
}
@end

void do_some_lengthy_cancelable_operation (id operation)
{
  for (int i = 0; i http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Quicklook thumbnails vs previews, API for previews?

2011-06-29 Thread Oleg Krupnov
Hi,

The QuickLook API documentation defines and contrasts "thumbnails" and
"previews", but all I see on the client side is the only function
QLThumbnailImageCreate. I assume this is for creating "thumbnails",
isn't it? In that case, how do I create "previews" on the client side?
Alternatively, if this function is meant for creating both thumbnails
and previews, is there a way to force create thumbnail or preview?

Thanks.

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Referencing struct fields in C

2011-05-30 Thread Oleg Krupnov
> In any case, the optimizer will probably move all of the loop-invariant state 
> outside the loop for you, and it's likely to do a better job than your 
> home-grown attempt.

That's a great news! If it is really so, I stand corrected and not
trying to optimize it any further.

In fact, in the meantime I created a quick and dirty prototype to
measure this operation isolated, and it seems that out of 3 options
(plain if, function pointer, and pointer arithmetics) the plain if is
the winner, surprisingly :)

I also agree with what you said about negligibility of this
optimization compared to the rest of code. It's just sometimes hard to
stop nit-picking where you think you can optimize something, you know
:)

One thing that bothers me though. How the compiler will understand
that the state is loop-invariant? Should I necessarily declare the
checked boolean state as a local stack variable (unlike to a class
member variable that may change as a side-effect, if foo() was a class
method)?

for example
- (void)foo
{
   bool xOrY = m_isXOrY;
   for (int i = 0; i < N; ++i)
  {
 if (xOrY)
 {
 int value = a[i].y;
  ...
 }
 else
 {
 int value = a[i].y;
 ...
 }
  }
}

Would this suffice?

Thanks!

On Mon, May 30, 2011 at 4:14 PM, Graham Cox  wrote:
>
> On 30/05/2011, at 10:26 PM, Oleg Krupnov wrote:
>
>> I knew this question was coming! :) Well, maybe you are right. The
>> problem is that the function foo() involves much stuff, including disk
>> I/O operations, so measuring its performance is quite tricky, you get
>> different result on each test, depending on the available memory, disk
>> busyness etc. It's hard to make a clean experiment. Generally, the
>> foo() needs to be as fast as possible, because it is already long
>> lasting. I have been optimizing foo() before, and now I need to make
>> only a small change (choose x or y), and I am lazy to bother with
>> profiling again, I just wanted to make the most optimal possible thing
>> up front. Maybe it's just nit-picking... But I became curious if the
>> above idea would be feasible at all!
>
>
> This suggests that the optimisation you're contemplating is not going to be 
> worthwhile. The tiny gains you might see due to eliminating one 
> test-and-branch per loop are going to be swamped massively by these other 
> things going on. It's not a case of not making a clean experiment, it's not 
> going to be measurable*. In any case, the optimizer will probably move all of 
> the loop-invariant state outside the loop for you, and it's likely to do a 
> better job than your home-grown attempt.
>
> That said, I'm not sure how portable it is, but you could use offsetof() 
> instead of pointer arithmetic, which is always a risky business.
>
> *Let's put some hypothetical numbers on this. Suppose your loop on its own, 
> doing nothing else, takes 1mS. Your optimisation goes in and hey-presto, it 
> takes 0.5mS. That looks great, a 100% improvement. Now add in all the "real 
> world" code that has to be executed. It now takes 5 seconds. The 0.5mS you 
> got is now a 0.01% improvement. QED.
>
> --Graham
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Referencing struct fields in C

2011-05-30 Thread Oleg Krupnov
I knew this question was coming! :) Well, maybe you are right. The
problem is that the function foo() involves much stuff, including disk
I/O operations, so measuring its performance is quite tricky, you get
different result on each test, depending on the available memory, disk
busyness etc. It's hard to make a clean experiment. Generally, the
foo() needs to be as fast as possible, because it is already long
lasting. I have been optimizing foo() before, and now I need to make
only a small change (choose x or y), and I am lazy to bother with
profiling again, I just wanted to make the most optimal possible thing
up front. Maybe it's just nit-picking... But I became curious if the
above idea would be feasible at all!

Thanks Graham!

On Mon, May 30, 2011 at 3:16 PM, Graham Cox  wrote:
>
> On 30/05/2011, at 10:10 PM, Oleg Krupnov wrote:
>
>>> I am looking to optimize this code
>
>
> Have you measured it and shown it to be a bottleneck, or are you just 
> assuming it will benefit?
>
> --Graham
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Referencing struct fields in C

2011-05-30 Thread Oleg Krupnov
And no, I cannot move the for loop inside the if, because the
(omitted) code inside the for loop is huge, and I would hate to
duplicate it in the both if clauses...


Thanks Dmitry!


On Mon, May 30, 2011 at 3:12 PM, Dmitry Muraviev  wrote:
> А почему вы не хотите перенести цикл внутрь условия?
>
>
>
> On 2011/May/30, at 16:02:09, Oleg Krupnov wrote:
>
>> This question is related to C language, rather than Obj-C.
>>
>> I have a data structure
>>
>> typedef struct
>> {
>>  int x;
>>  int y;
>> } A;
>>
>> In my code, I have a function foo(bool xOrY) that runs a long-lasting
>> loop that iterates through a huge array of A structures and for each
>> structure, it should get x or y field. The choice of x or y is the
>> same on each iteration, but may change between different calls of
>> foo(bool xOrY).
>>
>> void foo(bool xOrY)
>> {
>>  for(int i = 0; i < count; ++i)
>>  {
>>     if (xOrY)
>>     {
>>         int value = a[i].y;
>>         ...
>>     }
>>     else
>>     {
>>         int value = a[i].x;
>>         ...
>>     }
>>  }
>> }
>>
>> I am looking to optimize this code, because the line if(xOrY) yields
>> the same result on each step. So I am thinking about this code:
>>
>>
>> void foo(bool xOrY)
>> {
>>  struct A test;
>>  size_t offset = 0;
>>  if (xOrY)
>>  {
>>     offset = (char*)&(a.y) - (char*)&a;
>>  }
>>  else
>>  {
>>     offset = (char*)&(a.x) - (char*)&a;
>>  }
>>
>>  for(int i = 0; i < count; ++i)
>>  {
>>         int value = *(int*)((char*)a + offset);
>>  }
>> }
>>
>>
>> Is this approach valid at all? The compiler doesn't show any problem,
>> but I wonder if there can be any caveats related to structure aligning
>> etc.? It seems like it should not be a problem, because I am measuring
>> the offset in run time, but I am not quite sure...
>>
>> I also thought about using a function pointer to switch between two
>> tiny functions, one of them returning x and the other y from a given
>> struct instance, but it seems somewhat more expensive than the above
>> approach (push/pop param from stack, call, return)
>>
>> Thanks a lot!
>> ___
>>
>> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>> http://lists.apple.com/mailman/options/cocoa-dev/muravievd%40gmail.com
>>
>> This email sent to muravi...@gmail.com
>
> Best regards,
>
> Dmitry Muraviev
> Software Engineer
> Vidau Systems
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Referencing struct fields in C

2011-05-30 Thread Oleg Krupnov
oops, small correction, in the second code sample it should read:

 if (xOrY)
  {
 offset = (char*)&(test.y) - (char*)&test;
  }
  else
  {
 offset = (char*)&(test.x) - (char*)&test;
  }


On Mon, May 30, 2011 at 3:02 PM, Oleg Krupnov  wrote:
> This question is related to C language, rather than Obj-C.
>
> I have a data structure
>
> typedef struct
> {
>   int x;
>   int y;
> } A;
>
> In my code, I have a function foo(bool xOrY) that runs a long-lasting
> loop that iterates through a huge array of A structures and for each
> structure, it should get x or y field. The choice of x or y is the
> same on each iteration, but may change between different calls of
> foo(bool xOrY).
>
> void foo(bool xOrY)
> {
>   for(int i = 0; i < count; ++i)
>   {
>      if (xOrY)
>      {
>          int value = a[i].y;
>          ...
>      }
>      else
>      {
>          int value = a[i].x;
>          ...
>      }
>   }
> }
>
> I am looking to optimize this code, because the line if(xOrY) yields
> the same result on each step. So I am thinking about this code:
>
>
> void foo(bool xOrY)
> {
>   struct A test;
>   size_t offset = 0;
>   if (xOrY)
>   {
>      offset = (char*)&(a.y) - (char*)&a;
>   }
>   else
>   {
>      offset = (char*)&(a.x) - (char*)&a;
>   }
>
>   for(int i = 0; i < count; ++i)
>   {
>          int value = *(int*)((char*)a + offset);
>   }
> }
>
>
> Is this approach valid at all? The compiler doesn't show any problem,
> but I wonder if there can be any caveats related to structure aligning
> etc.? It seems like it should not be a problem, because I am measuring
> the offset in run time, but I am not quite sure...
>
> I also thought about using a function pointer to switch between two
> tiny functions, one of them returning x and the other y from a given
> struct instance, but it seems somewhat more expensive than the above
> approach (push/pop param from stack, call, return)
>
> Thanks a lot!
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Referencing struct fields in C

2011-05-30 Thread Oleg Krupnov
This question is related to C language, rather than Obj-C.

I have a data structure

typedef struct
{
   int x;
   int y;
} A;

In my code, I have a function foo(bool xOrY) that runs a long-lasting
loop that iterates through a huge array of A structures and for each
structure, it should get x or y field. The choice of x or y is the
same on each iteration, but may change between different calls of
foo(bool xOrY).

void foo(bool xOrY)
{
   for(int i = 0; i < count; ++i)
   {
  if (xOrY)
  {
  int value = a[i].y;
  ...
  }
  else
  {
  int value = a[i].x;
  ...
  }
   }
}

I am looking to optimize this code, because the line if(xOrY) yields
the same result on each step. So I am thinking about this code:


void foo(bool xOrY)
{
   struct A test;
   size_t offset = 0;
   if (xOrY)
   {
  offset = (char*)&(a.y) - (char*)&a;
   }
   else
   {
  offset = (char*)&(a.x) - (char*)&a;
   }

   for(int i = 0; i < count; ++i)
   {
  int value = *(int*)((char*)a + offset);
   }
}


Is this approach valid at all? The compiler doesn't show any problem,
but I wonder if there can be any caveats related to structure aligning
etc.? It seems like it should not be a problem, because I am measuring
the offset in run time, but I am not quite sure...

I also thought about using a function pointer to switch between two
tiny functions, one of them returning x and the other y from a given
struct instance, but it seems somewhat more expensive than the above
approach (push/pop param from stack, call, return)

Thanks a lot!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to use inline functions

2011-01-13 Thread Oleg Krupnov
Hi,

I realize that my question has no relation to Cocoa, but it's still
the place where I can get the fastest answer :)

In several places in my app I check if the user has a valid license
for my app. I'd like to make cracking the app somewhat more difficult
and rather than calling -[license isValid], I want to call
isLicenseValid(), and inline this function, so that the entire code of
this function is duplicated in the binary in each place where I make
the call to isLicenseValid().

How should I declare the function in this case?

I have made an h-file and put the body of the function there:

(LicenseValidation.h)

inline bool isLicenseValid()
{
   ...
   return isValid;
}

But when I #include this h-file into an m-file where I need it, the
compiler says "Symbol not found, _isLicenseValid referenced from ..."

So I added "static" to the declaration :

static inline bool isLicenseValid()
{
   ...
   return isValid;
}

No more errors, but I am not sure if in this case the compiler will
produce as many instances of the code as there are calls to the
function. Will it?

Thanks!

P.S. I am using a GCC compiler
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Change duration of a running CAAnimation?

2010-11-26 Thread Oleg Krupnov
Thanks Matt! I have already found another solution that worked pretty
well: Instead of using the repeatCount property, I set a delegate on
the animation and add another animation manually each time the
previous one ends (animationDidEnd: finished:). In this way I can
fully control the fromValue and toValues of each loop of the
animation.

On Fri, Nov 26, 2010 at 6:51 PM, Matt Neuburg  wrote:
> On Thu, 25 Nov 2010 20:40:57 +0200, Oleg Krupnov  
> said:
>>Is there a way to change the duration of an already running
>>CAAnimation, in order to change its speed?
>>
>>The animation is added explicitly via [layer addAnimation: forKey:]
>>
>>When I try to get the animation with [layer animationForKey:] and call
>>[animation setDuration:], I get an exception that I'm trying to modify
>>a readonly animation.
>>
>>I know I could cancel the current animation and start a new one using
>>the current [layer presentationLayer]'s value as the fromValue, but
>>this is not convenient because my animation is repetitive and after
>>such a manipulation it will start from a wrong fromValue on the next
>>loop.
>
> Nevertheless that's what you're probably going to have to do. The 
> +timeOffset+ property may assist you here in starting the new animation "in 
> the middle"; also, observe that +repeatCount+ is a float (it does not have to 
> indicate an integral number of repetitions). m.
>
> --
> matt neuburg, phd = m...@tidbits.com, <http://www.apeth.net/matt/>
> A fool + a tool + an autorelease pool = cool!
> AppleScript: the Definitive Guide - Second Edition!
> http://www.apeth.net/matt/default.html#applescriptthings
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Change duration of a running CAAnimation?

2010-11-25 Thread Oleg Krupnov
Hi,

Is there a way to change the duration of an already running
CAAnimation, in order to change its speed?

The animation is added explicitly via [layer addAnimation: forKey:]

When I try to get the animation with [layer animationForKey:] and call
[animation setDuration:], I get an exception that I'm trying to modify
a readonly animation.

I know I could cancel the current animation and start a new one using
the current [layer presentationLayer]'s value as the fromValue, but
this is not convenient because my animation is repetitive and after
such a manipulation it will start from a wrong fromValue on the next
loop.

Thanks!

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Variable declaration in "for" loop initialization expression?

2010-11-18 Thread Oleg Krupnov
Thanks Graham!

I think I will stick to the more restricted version. It's more compact
and reliable indeed.

It seems that C99 is set by default in XCode. What are the possible
scenarios when I may need to use another dialect?

Oleg.

On Thu, Nov 18, 2010 at 1:52 PM, Graham Cox  wrote:
>
> On 18/11/2010, at 10:47 PM, Graham Cox wrote:
>
>> I don't think there is any significant advantage to either form, except the 
>> latter is perhaps a bit more compact in source code. It shouldn't make any 
>> difference to the object code.
>
>
> I should also point out that there is a scope difference - in the second form 
> the counter variable only has the scope of the for{...} statement whereas the 
> first form has the scope of the enclosing statement. Arguably the more 
> restricted scoping can help eliminate bugs.
>
> --Graham
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Variable declaration in "for" loop initialization expression?

2010-11-18 Thread Oleg Krupnov
Hi,

I know, this is a very basic question, but after learning so many
programming languages, my head seems like a mess.

In C that is in Objective-C, what is the correct/preferable way to
declare the counter variable in a for loop?

Type i;
for (i = 0; i < N; ++ i) { statements }

or

for (Type i = 0; i < N; ++i) { statements }



Regarding for...in... loop, the docs are very clear that both the
following declarations are valid:

Type existingItem;
for ( existingItem in expression ) { statements }

and

for ( Type newVariable in expression ) { statements }

But what about for (;;) ? The compiler does not point to it as an
error if I declare the counter inside the for () brackets, but I want
to make sure!

Thanks

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Threads and run loops

2010-11-05 Thread Oleg Krupnov
Sure! I should make myself clear, when I said "the other thread enters
its run loop", I meant that the thread executes some my code in its
"main" that does some setup and enters the run loop. I didn't mean it
happens automatically. But the questions remain.

On Fri, Nov 5, 2010 at 10:08 AM, Vincent Habchi  wrote:
> Le 5 nov. 2010 à 08:29, Oleg Krupnov a écrit :
>
>> Hi,
>>
>> I've got a couple of questions:
>>
>> 1. What happens if I send a message via -performSelector:onThread:
>> from one thread to another, before the other thread has time to enter
>> its run loop? Is the message going to be lost?
>>
>> 2. Is there a way to wait and make sure the thread has entered its run
>> loop? How do I check if a thread has entered its run loop?
>
> AFAIK, you are responsible for setting up and launching threads run loop, so 
> that should not be an issue.
> Vincent
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Threads and run loops

2010-11-05 Thread Oleg Krupnov
Hi,

I've got a couple of questions:

1. What happens if I send a message via -performSelector:onThread:
from one thread to another, before the other thread has time to enter
its run loop? Is the message going to be lost?

2. Is there a way to wait and make sure the thread has entered its run
loop? How do I check if a thread has entered its run loop?


Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


[SOLVED] Re: [Distant Objects] Problem passing custom objects bycopy

2010-10-19 Thread Oleg Krupnov
I have been able to figure out the problem myself. Here is the
solution for anyone interested.

To diagnose the problem, I tried to send a test object bycopy to the
server, instead of receiving an object bycopy from the server. It
allowed me to locally debug what's happening when
-replacementObjectForPortCoder: is called.

The problem was that I used NSCoder's -[encode***: forKey:], whereas
it turns out that the NSPortCoder does not support it, so an exception
occurred. It only supports encoding C-types
-encodeValueOfObjCType:at:, -encodeValuesOfObjCTypes:...,
-encodeArrayOfObjCType:count:at:, -encodeObject: and their decode*
counterparts. The last encodeObject/decodeObject method processes
object members recursively.

For my application it's okay to not use keys in encoding/decoding, so
it solved the problem.

Oleg.

On Mon, Oct 18, 2010 at 6:46 PM, Oleg Krupnov  wrote:
> Hi,
>
> I have a server and a client processes running on the same machine.
> Per client request, the server does some job and returns the result to
> the client in form of some MyObject.
>
> This is the interface vended by the server:
>
> - (out bycopy MyObject*)doSomeJob;
>
> Despite bycopy, I see in debugger that instead of a copy, a proxy is returned.
>
> Allright, I've read in this list that in order to make work, I also
> need to override -replacementObjectForPortCoder: and I did this:
>
> // in MyObject
> - (id)replacementObjectForPortCoder:(NSPortCoder*)encoder
> {
>        if ([encoder isBycopy])
>        {
>                 NSLog(@"replace by copy!!!")
>                return self;
>        }
>        return [super replacementObjectForPortCoder:encoder];
> }
>
> In this case, I see the "replace by copy!!!" string in the console,
> but then the server process seems to hang and become unresponsive.
> -[MyObject encodeWithCoder:] does not get called.
>
> What am I doing wrong?
>
> Thanks!
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


[Distant Objects] Problem passing custom objects bycopy

2010-10-18 Thread Oleg Krupnov
Hi,

I have a server and a client processes running on the same machine.
Per client request, the server does some job and returns the result to
the client in form of some MyObject.

This is the interface vended by the server:

- (out bycopy MyObject*)doSomeJob;

Despite bycopy, I see in debugger that instead of a copy, a proxy is returned.

Allright, I've read in this list that in order to make work, I also
need to override -replacementObjectForPortCoder: and I did this:

// in MyObject
- (id)replacementObjectForPortCoder:(NSPortCoder*)encoder
{
if ([encoder isBycopy])
{
 NSLog(@"replace by copy!!!")
return self;
}
return [super replacementObjectForPortCoder:encoder];
}

In this case, I see the "replace by copy!!!" string in the console,
but then the server process seems to hang and become unresponsive.
-[MyObject encodeWithCoder:] does not get called.

What am I doing wrong?

Thanks!
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Instantly delete a directory without recursion?

2010-10-04 Thread Oleg Krupnov
Thanks everyone! Now I see.

Oleg.

On Mon, Oct 4, 2010 at 4:14 PM, Kirk Kerekes  wrote:
>> Is there a way to delete a directory instantly and completely without
>> first deleting all its subdirectories and files recursively?
>
> The hierarchical structure that you see is not "real" -- directories are not 
> physical containers for the files that they appear to contain. The directory 
> hierarchy is a carefully maintained fiction.
>
> Irrelevant aside:
>   The original Mac file system took this a step further -- it made the 
> directory structure
>   totally a visual fiction -- all of the files were at the root of the (3.5") 
> floppy)
>   disk, and only _seemed_ to be arranged in folders. Thankfully this was 
> supplanted by HFS.
>
> It is better to think of directories/folders as a special kind of file that 
> contains an index to a set of files that it is going to _pretend_ to contain.
>
> Conceptually, this works much like classical Cocoa memory management. Each 
> (directory/object) "owns" a set of (files/objects) by reference ("retains" 
> the (file/object)).
>
> When you delete a file from a directory, it is "released". If no other 
> directory has an ownership claim on that file, it is "dealloc'ed".
>
> Your (folder/object) doesn't contain the objects that it "owns". It doesn't 
> really even "own" them -- it just has a "ownership claim" on them.
>
> From Wikipedia's article about Hard Links:
>
>> "a hard link is a directory entry that associates a name with a file on a 
>> file system. A directory is itself a special kind of file that contains a 
>> list of such entries."
>
> Note that due to the use of hard links it is possible to have a single 
> physical file that can appear in multiple directories. Each one of those 
> directories owns a reference to the "real" file. Each reference is as "real" 
> as any other. All references have to be "unlinked" for the file to be marked 
> as deleted.
>
> The "file" can even have different "names" in the different directories!
>
> Hard links are the chain  saw of filesystem features -- powerful, but 
> potentially quite dangerous. Note that the OSX GUI provides no means of 
> producing hard links, or even symlinks.
>
>
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Instantly delete a directory without recursion?

2010-10-04 Thread Oleg Krupnov
Let me make the question more clear: I am aware of functions like
[NSFileManager removeItemAtPath: error:], but what they do under the
hood is they iterate through the subdirectories and files and delete
them first. This takes some time. I am interested if it is possible to
do this instantly, without even implicit recursion. Just remove the
directory and the files and subdirectories would disappear?

Thanks!

On Mon, Oct 4, 2010 at 11:03 AM, Oleg Krupnov  wrote:
> Hi,
>
> Is there a way to delete a directory instantly and completely without
> first deleting all its subdirectories and files recursively?
>
> Thanks.
>
> Oleg.
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Instantly delete a directory without recursion?

2010-10-04 Thread Oleg Krupnov
Hi,

Is there a way to delete a directory instantly and completely without
first deleting all its subdirectories and files recursively?

Thanks.

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Instantly delete a directory without recursion?

2010-10-04 Thread Oleg Krupnov
Hi Guillem,

You are correct, in many cases the number of files will not be big, so
it should not matter too much, but using the opportunity, I decided to
illuminate myself regarding the possibilities there are in the file
system.

I had an idea that because the directory tree is growing from a single
root, there *might* be a possibility to axe it off with a single hit.
Is it possible?

Thanks.

On Mon, Oct 4, 2010 at 11:18 AM, Guillem Palou  wrote:
> When removing directories, the OS should remove all the tree created in the 
> filesystem. I think you cannot do anything else?
> Is it so critical? How many files do you have to delete?
>
> On Oct 4, 2010, at 10:12 AM, Oleg Krupnov wrote:
>
>> Let me make the question more clear: I am aware of functions like
>> [NSFileManager removeItemAtPath: error:], but what they do under the
>> hood is they iterate through the subdirectories and files and delete
>> them first. This takes some time. I am interested if it is possible to
>> do this instantly, without even implicit recursion. Just remove the
>> directory and the files and subdirectories would disappear?
>>
>> Thanks!
>>
>> On Mon, Oct 4, 2010 at 11:03 AM, Oleg Krupnov  wrote:
>>> Hi,
>>>
>>> Is there a way to delete a directory instantly and completely without
>>> first deleting all its subdirectories and files recursively?
>>>
>>> Thanks.
>>>
>>> Oleg.
>>>
>> ___
>>
>> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>> http://lists.apple.com/mailman/options/cocoa-dev/guillem.palou%40gmail.com
>>
>> This email sent to guillem.pa...@gmail.com
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-30 Thread Oleg Krupnov
Hi Ken,

I've tried sockets instead of mach ports, but the result is almost the
same. At first, the request via the new connection was handled in the
new server thread, which rejoiced me, but then the second request to
the same connection from the same client thread was handled in the
main server thread again. The threads seem to be picked arbitrary as
well as in the case of mach ports :(

I have a strange idea, but if it would be possible, it could solve the
problem. Can I, hem, just launch a new server thread and create
another connection point, and register it under a different name, and
vend another root object through it (different instance of different
class) and then launch a run loop in that thread?

Here is the code:

- (void)threadMain
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

NSConnection* connectionPoint = [[NSConnection new] autorelease];

NSProtocolChecker* vendedThreadObject = [NSProtocolChecker
protocolCheckerWithTarget:self
protocol:@protocol(ThreadObjectProtocol)];

[connectionPoint setRootObject:vendedThreadObject];

if ([connectionPoint registerName:@"anotherName02"])
{   
while (!isTerminated)
{
[[NSRunLoop currentRunLoop] run];
}
}

[pool release];
}

However, the line "registerName" returns NO. What is the problem?

Thanks,

Oleg.


On Thu, Sep 30, 2010 at 7:45 PM, Ken Thomases  wrote:
> On Sep 30, 2010, at 11:17 AM, Oleg Krupnov wrote:
>
>> NSSocketPort* port = [[NSSocketPort alloc] initWithTCPPort:1234];
>> NSConnection* connectionPoint = [[NSConnection alloc]
>> initWithReceivePort:port sendPort:nil];
>> if ([connectionPoint registerName:CONNECTION_NAME
>> withNameServer:[NSSocketPortNameServer sharedInstance]])
>>
>> This time it registered, but on client side I get nil when asking for proxy:
>>
>> proxy = [NSConnection
>> rootProxyForConnectionWithRegisteredName:CONNECTION_NAME host:nil];
>>
>> I get nil. I tried "localhost" and "128.0.0.1" for host, but still no luck.
>
> Try +rootProxyForConnectionWithRegisteredName:host:usingNameServer: and 
> specify the socket port name server (similar to what you did, above).
>
>> There must be something simple I've overlooked? The docs do not tell
>> how to set up sockets easily, only Mach ports come by default...
>
> There are multiple approaches.  You can use the initializers of NSSocketPort 
> to create socket ports.  You can use one of the -portForName:... methods of 
> NSSocketPortNameServer to obtain a socket port for communicating with the 
> named service.
>
> Once you have the socket ports, you can create NSConnection objects from 
> them, as you did above.
>
> Cheers,
> Ken
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-30 Thread Oleg Krupnov
Hi Ken,

I understand that you probably cannot help me any further, but just in
case I am reporting the following, if anyone knows a solution or can
benefit from the information

I have checked the mailing archives and it seems that I am not alone
with the problem that runInNewThread does not necessarily cause the
request to be processed in the new thread. Some folks report that
-removeRunLoop helped them, but my experiments show that

1. -removeRunLoop doesn't seem to have any reproducible effect. At
times it works, other times not.

2. Even two subsequents calls via the same NSConnection (for which
-removeRunLoop: and -runInNewThread was called) are not guaranteed to
be handled in the same server thread. The server seems to freely pick
any idle threads that from the ones that are currently running.

3. What is curious, the #2 also happens if instead of -runInNewThread,
I create a thread manually via [NSThread
detachNewThreadSelector:toTarget:withObject:] and [NSConnection
addRunLoop:]. This is very weird -- the server utilizes any threads
you create!

4. Because server threads are assigned to connection requests so
arbitrary, it seems dangerous to manually quit any thread. It may be
being used by the server at the moment at its discretion. This means
effectively, that there is no way to exit unneeded threads on server,
only to launch new.

I have two assumptions:

1. There is [NSConnection multipleThreadsEnabled] that may be causing
this behavior. Unfortunately, there is no way to turn it off, there is
only -enableMultipleThreads, and by default it is on starting from
10.5. I wished there were disableMultipleThreads to try!

2. Can it happen because all connections on the server share the same
receiving port, which is added to the main run loop?


Thanks,

Oleg.



On Thu, Sep 30, 2010 at 3:04 AM, Ken Thomases  wrote:
> Hi Oleg,
>
> On Sep 29, 2010, at 9:57 AM, Oleg Krupnov wrote:
>
>> I tried -[NSConnection removeRunLoop:[NSRunLoop currentRunLoop]], but
>> it doesn't seem to change anything.
>
> Huh.  I don't know what's going on there.  You might consider opening a 
> developer technical support incident with Apple to ask them for advice on how 
> to achieve what you want.  Those cost money, but probably not as much as your 
> time.
>
>
>> Well, I could live with it, because the server already works as
>> multi-threaded, but the problem is that the new thread that is
>> spawned, is not released if the request is handled in the main thread,
>> when I call -invalidate on the connection. And there does not seem a
>> way to get the thread created by runInNewThread to exit it manually,
>> or is there?
>
> Probably not, but you could re-implement -runInNewThread and make 
> arrangements to terminate the thread on other occasions.
>
> I think that an alternative implementation should just remove the connection 
> from the current run loop and spawn a new thread.  The method of the new 
> thread would add the connection to its run loop and run the run loop 
> indefinitely.  You could change that to add your own signaling mechanism so 
> that, when signaled, the thread would exit instead of looping through the run 
> loop again.
>
> Regards,
> Ken
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-29 Thread Oleg Krupnov
Hi Ken,

> I'm not sure exactly what's happening.  It sounds like the connection's ports 
> are still scheduled in the main thread's run loop as well as the new thread's 
> run loop.  When a request arrives and both run loops are idle, it's 
> effectively arbitrary which one will handle the request.  I would have 
> thought that -runInNewThread would do this implicitly, but you may have to 
> use -[NSConnection removeRunLoop:[NSRunLoop currentRunLoop]] to remove the 
> connection's ports from the run loop of the main thread (or whichever thread 
> the check-in message is handled by).

I tried -[NSConnection removeRunLoop:[NSRunLoop currentRunLoop]], but
it doesn't seem to change anything.

Well, I could live with it, because the server already works as
multi-threaded, but the problem is that the new thread that is
spawned, is not released if the request is handled in the main thread,
when I call -invalidate on the connection. And there does not seem a
way to get the thread created by runInNewThread to exit it manually,
or is there?

Thanks,

Oleg.

On Wed, Sep 29, 2010 at 2:22 PM, Ken Thomases  wrote:
> Hi Oleg,
>
> On Sep 29, 2010, at 5:16 AM, Oleg Krupnov wrote:
>
>> Now I see. I hardly find words to thank you for your patience! :)
>
> You're welcome.  I'm glad I could help.
>
>
>> Now I see that the correct picture is the following. There is only one
>> connection point, and there is only one root vended object in the
>> server. I need only to make sure that each client thread uses a
>> different connection object, though all connections use the same
>> connection point and send port on server (addressed by its single
>> registered name).
>
> In the server, it is the receive port which is registered under a name.  The 
> server "receives" connections from clients on that port.  (Actually, reading 
> the docs for -initWithReceivePort:sendPort:, the server's connection point 
> typically uses the same port for receive and send.)
>
>> In other words, this new connection is like a
>> parallel channel to the same root vended object. So when I call
>> rootProxy on the new connection on client, I obtain the same root
>> proxy (not the per-thread proxy that I initially thought of).
>
> You should receive a different proxy to the same root object.  (The root 
> proxy is an NSDistantObject that is specific to the connection.  So, a 
> different connection implies a different proxy object.)
>
> But you are correct that the design has a single root object in the server, 
> not multiple root objects, one for each client connection.
>
>> Then I
>> ask this root proxy to take the current connection and detach it to a
>> new thread. Objects and threads are fully orthogonal.
>
> Well, the client shouldn't be aware that its check-in message has the result 
> of spawning a new thread in the server.  The check-in message should just be 
> a way for the client to make the server aware of it, and to initiate service 
> for it (whatever "service" means in your application).  The server could be 
> designed either way, with a separate thread per client connection or all 
> handled by one thread.
>
> If having a single root object feels cumbersome, the root object could be 
> turned into just a factory for per-client service objects.  So, the client 
> checks in and asks the single root object for a new object which will serve 
> just it (that specific client; I consider each thread within the client 
> process to be a separate "client" in your design).  The server creates a new 
> object to satisfy that request, and that new object would be initialized with 
> whatever state is specific to that client.  It would also happen to spin off 
> a separate thread to handle communications with that client, but that's an 
> implementation detail.
>
>
>> Of course, I've read all docs, but I found them quite scarce and even
>> confusing at times. Only with your help, and with some knowledge of
>> sockets I have, I went down to the basics and became able to
>> understand how it works under the hood.
>
> OK.  I can definitely see how the docs can be confusing or less than 
> thorough.  I recommend that you file requests for enhancements to anything 
> you didn't understand.
>
>> For example, the docs say
>> nothing about the notion of connection points as opposed to child
>> connections. It calls everything a "NSConnection" and this was my
>> source of confusion.
>
> They do say "the connection labeled s is used to form new connections" and "A 
> named connection rarely has a channel to any other NSConnection ob

Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-29 Thread Oleg Krupnov
Hi Ken,

Now I see. I hardly find words to thank you for your patience! :)

There's been indeed a misunderstanding. I imagined mistakenly that
there could be many "connection points" on the server, one connection
point per thread, and each such connection point could vend a
different object of different type. So I was looking for a way to pass
"address" of this new connection point (like the registered name for
the main one) to the client thread, so that it could call a method
similar to rootProxyForConnectionWithRegisteredName on it.

Now I see that the correct picture is the following. There is only one
connection point, and there is only one root vended object in the
server. I need only to make sure that each client thread uses a
different connection object, though all connections use the same
connection point and send port on server (addressed by its single
registered name). In other words, this new connection is like a
parallel channel to the same root vended object. So when I call
rootProxy on the new connection on client, I obtain the same root
proxy (not the per-thread proxy that I initially thought of). Then I
ask this root proxy to take the current connection and detach it to a
new thread. Objects and threads are fully orthogonal.

Of course, I've read all docs, but I found them quite scarce and even
confusing at times. Only with your help, and with some knowledge of
sockets I have, I went down to the basics and became able to
understand how it works under the hood. For example, the docs say
nothing about the notion of connection points as opposed to child
connections. It calls everything a "NSConnection" and this was my
source of confusion.

There is only one problem left: logs show that although I obtain the
root proxy for the new connection and call a worker method on it in
client, the server still uses the main thread to respond, instead of
the newly created connection's thread. More experiment shows that when
there is already a busy server thread, then the server uses the new
thread, but when there are no other threads, the main thread is used.
Is it a kind of optimization the framework does, or is it my bug? I'd
like that each client thread only worked with its dedicated server
thread and did not mess with the server's main thread.

Thank you again,

Oleg.

On Wed, Sep 29, 2010 at 3:26 AM, Ken Thomases  wrote:
> On Sep 28, 2010, at 1:23 PM, Oleg Krupnov wrote:
>
>> So, let's assume I create the connection in this way:
>>
>> NSConnection* connection = [NSConnection connectionWithReceivePort:nil
>> sendPort:[[NSMachBootstrapServer sharedInstance] portForName:@"foo"]];
>>
>> or even
>>
>> NSConnection* connection = [NSConnection
>> connectionWithReceivePort:[NSMachPort port] sendPort:[NSMachPort
>> port]];
>>
>> Then I vend the object:
>>
>> [connection setRootObject:serverObject];
>>
>> And finally launch it in a separate thread:
>>
>> [connection runInNewThread];
>>
>> But how do I pass this connection back to client so that I could call
>> -rootProxy on it?
>
> You don't.  Please reread what I wrote.  My last email was largely about how 
> the client creates its connection.  You've misunderstood it to be about how 
> the server creates it.  (The above approaches wouldn't even work for a 
> server.)
>
> Servers don't create connections to clients.  Clients create connections to 
> servers.
>
> A server only explicitly creates a single NSConnection instance.  This isn't 
> a connection so much as a "connection point" -- a place where clients can 
> connect to.
>
> Then, clients create connections to the server.  In response, in the server, 
> the frameworks implicitly create new NSConnection instances for each client 
> connection.  Once again, this is clearly illustrated in the documentation on 
> Distributed Objects.  Have you read it?
> <http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/DistrObjects/Concepts/connections.html>
>
> We've already discussed how and when the server tells the newly-created 
> connections to run in a separate thread.
>
> The only complication is that, because your clients are attempting to make 
> multiple connections from the same process, and because the frameworks try to 
> reuse connections within a process, you have to take some minor extra 
> precautions to make sure you are getting separate, independent connections to 
> the server.  I have told you how to do that.
>
>> That was actually the original question in the
>> subject of this mail :)
>
> Not as I understood it.  And if it was, then you have a fundamental 
> misunderstanding about how connections work.  Again: servers don't

Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-28 Thread Oleg Krupnov
Ken,

So, let's assume I create the connection in this way:

NSConnection* connection = [NSConnection connectionWithReceivePort:nil
sendPort:[[NSMachBootstrapServer sharedInstance] portForName:@"foo"]];

or even

NSConnection* connection = [NSConnection
connectionWithReceivePort:[NSMachPort port] sendPort:[NSMachPort
port]];

Then I vend the object:

[connection setRootObject:serverObject];

And finally launch it in a separate thread:

[connection runInNewThread];

But how do I pass this connection back to client so that I could call
-rootProxy on it? That was actually the original question in the
subject of this mail :)


The other question I've got is how do I exit the newly created thread
when its job is done?

Thanks,

Oleg.

On Tue, Sep 28, 2010 at 11:11 AM, Ken Thomases  wrote:
> On Sep 28, 2010, at 2:29 AM, Oleg Krupnov wrote:
>
>> Thanks Ken,
>
> You're welcome.  I'm glad to help.
>
>
>> 1. What happens when I call -connectionForProxy on the client proxy
>> object? Is a new connection created? Or the root vended object's
>> connection can be reused? In the latter case if I remove that
>> connection from the main run loop and call -runInNewThread, would the
>> root object's operation be broken?
>
> The server creates one NSConnection instance and registers it under a name.  
> This connection doesn't actually send data to any client.  It listens for 
> connections from clients and, when one connects, creates a new NSConnection 
> instance to conduct the communication with that client.  The new NSConnection 
> is a child of the original one.  (If you've ever worked with BSD sockets, 
> this should be familiar.  The server creates one socket file descriptor with 
> the socket() call, calls bind() and listen() on it, and then accept()s new 
> file descriptors as connections are made.)
>
> The -connectionForProxy method returns the existing connection being used to 
> convey messages to the proxy to its distant "real" object.  This will be 
> different from the NSConnection object the server originally created and 
> registered.  It will be one of the child connections.
>
>
>> 2. I tried to launch two client threads simultaneously and pass
>> different objects to the check-in method, and I see that the
>> connection returned from -connectionForProxy is the same for the both
>> threads. Is it a problem? Won't the two threads somehow interfere?
>
> I believe you are being bitten by what I wrote about here:
>
>> On Tue, Sep 28, 2010 at 9:12 AM, Ken Thomases  wrote:
>>
>>> For a multi-threaded client which wants to have several connections to the 
>>> same server, you may have to jump through a couple of hoops.  NSConnection 
>>> is pretty eager about reusing its instances if they match a new request.  
>>> You may need to create the connection somewhat manually by creating the 
>>> ports and then explicitly using +connectionWithReceivePort:sendPort: or 
>>> -initWithReceivePort:sendPort:.
>
> Two threads within one process may very well get the same connection to the 
> server.  The simple methods for getting the connection (or ignoring the 
> connection and just getting the root proxy) just ask by name.  NSConnection 
> will realize it already has a connection for that name and reuse it.  So, you 
> probably shouldn't use:
>
> +connectionWithRegisteredName:host:
> +connectionWithRegisteredName:host:usingNameServer:
> +rootProxyForConnectionWithRegisteredName:host:
> +rootProxyForConnectionWithRegisteredName:host:usingNameServer:
>
> Instead, you should create two ports of the appropriate type.  If you're 
> using Mach ports for communication, then you want NSMachPorts.  If you're 
> using sockets for communication, then NSSocketPorts.
>
> You should get the send port from the appropriate port name server.  For 
> example, [[NSMachBootstrapServer sharedInstance] portForName:@"foo"] or 
> [[NSSocketPortNameServer sharedInstance] portForName:@"foo" 
> host:@"server.example.com"].  This send port is still likely to be shared by 
> the threads.
>
> So, you should create a separate receive port for each thread.  That's the 
> part which ensures that each thread has a separate NSConnection (both on the 
> client side and the server side).  For example [NSMachPort port] or 
> [NSSocketPort port].
>
> Then, you should create the connection to the server from those two ports, 
> using one of:
>
> +connectionWithReceivePort:sendPort:
> -initWithReceivePort:sendPort:
>
> Read the documentation for the latter of those to learn about NSConnection 
> object re-use/sharing.  Those docs suggest you may be a

Re: Acquiring an NSConnection otherwise than by registered name?

2010-09-28 Thread Oleg Krupnov
Thanks Ken,

I tried this:

> Your clients (each thread is a separate client, if you like) should be 
> checking in with the server by invoking a specific method on the root proxy.  
> They should be passing some object representing themselves to the server.  On 
> the server side, the check-in method will actually receive a proxy for the 
> client's object.  This will be an NSDistantObject.  The server can invoke 
> -connectionForProxy on it, then -runInNewThread on the connection.

And it seems to work. The client threads no longer block each other
when they need to request the server.

But let me ask a couple of questions, because I don't get how it works
and there might still be a problem in my code:

1. What happens when I call -connectionForProxy on the client proxy
object? Is a new connection created? Or the root vended object's
connection can be reused? In the latter case if I remove that
connection from the main run loop and call -runInNewThread, would the
root object's operation be broken?

2. I tried to launch two client threads simultaneously and pass
different objects to the check-in method, and I see that the
connection returned from -connectionForProxy is the same for the both
threads. Is it a problem? Won't the two threads somehow interfere?
AFAIR connections cannot be shared between different threads.

Here is my code of the check-in method of the root vended object on
the server side:

- (byref NSObject*)createServerObjectForClientObject:(byref
NSObject*)clientObject
{
NSConnection* connection = [(NSDistantObject*)clientObject 
connectionForProxy];
[connection removeRunLoop:[NSRunLoop mainRunLoop]];
[connection runInNewThread];

   // server object is a per-client-thread object on the server
side, not the root vended object
NSObject* serverObject = [[[VendedServerObject alloc]
init] autorelease];
return serverObject;
}

Thanks!

Oleg.

On Tue, Sep 28, 2010 at 9:12 AM, Ken Thomases  wrote:
> On Sep 28, 2010, at 12:24 AM, Oleg Krupnov wrote:
>
>> My question is: is it possible to acquire the connection in another
>> way than using a name?
>
> Yes, of course.  Have you looked at the NSConnection class reference, where 
> it documents multiple methods for obtaining connection objects?
>
> First of all, your server already has multiple connection objects.  The first 
> connection is like a listen socket.  As new clients connect, it accepts those 
> and creates a new child NSConnection for each.
>
>
>> Why I want this: My client process has many threads, and the server
>> process must create a thread for each client thread.
>
> Your clients (each thread is a separate client, if you like) should be 
> checking in with the server by invoking a specific method on the root proxy.  
> They should be passing some object representing themselves to the server.  On 
> the server side, the check-in method will actually receive a proxy for the 
> client's object.  This will be an NSDistantObject.  The server can invoke 
> -connectionForProxy on it, then -runInNewThread on the connection.
>
> At least, I'm pretty sure that will do what you want.  Another approach would 
> be for the server to set a delegate on the main connection and, each time it 
> is asked if it's OK to create a new connection for a new client (whether that 
> new client is a separate process or just a separate thread), your delegate 
> method can invoke -runInNewThread on the new connection.
>
> For a multi-threaded client which wants to have several connections to the 
> same server, you may have to jump through a couple of hoops.  NSConnection is 
> pretty eager about reusing its instances if they match a new request.  You 
> may need to create the connection somewhat manually by creating the ports and 
> then explicitly using +connectionWithReceivePort:sendPort: or 
> -initWithReceivePort:sendPort:.
>
> Regards,
> Ken
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Acquiring an NSConnection otherwise than by registered name?

2010-09-27 Thread Oleg Krupnov
Hi,

Here is the way to acquire connection from a server, as described in the docs:

NSConnection* theConnection = [NSConnection
connectionWithRegisteredName:@"server" host:nil];

My question is: is it possible to acquire the connection in another
way than using a name?

Why I want this: My client process has many threads, and the server
process must create a thread for each client thread. If I register all
connections by names, there's going to be many connections visible in
the system to other processes as well, and their names can clash etc.
My idea is to create a single named connection and then somehow pass
other connections through the first one.

Is this possible?

Can something like this be valid?

[pseudocode]
NSConnection* theConnection = (by ref)[rootProxy openNewConnection];

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Accessing NSDistantObject from different threads concurrently

2010-09-23 Thread Oleg Krupnov
So, how do I implement multiple threads in the server process?

I have the following idea:

Vend many objects. First, vend a root object in the server process and
then have it create new server threads by client request and return a
connection name to the client. The new server thread creates a
connection with the above name, and through it vends its per-thread
object, and then launches its run loop to listen to the connection.

Is this a valid approach?

What is nice about it, is that there is no trouble with
synchronization. The client thread first attempts to open the
connection by the name and simply blocks until it gets it without
blocking the main server thread nor the main client thread. However,
as I understand, these named connections are visible system-wide, so I
wonder if having too many named connections is expensive for the
system, isn't it?

I would appreciate comments or suggestions of other designs. Am I on
the right path at all?

Thanks,

Oleg.

On Mon, Sep 20, 2010 at 8:32 PM, Oleg Krupnov  wrote:
> Thanks, Kyle
>
>> Multithreading is not a prerequisite for serving multiple clients. Depending 
>> on what your server's doing, sticking with NSRunLoop-based multiplexing 
>> might be a lot easier.
>
> The server's job is associated with slow devices, such as disk, but
> are quite lengthy in time. In your scenario, all client threads will
> be unnecessarily waiting for the server to complete the current job,
> while there is still a lot of CPU time to run the other jobs
> concurrently.
>
>> The NSConnection documentation has a bunch of methods for dealing with 
>> multiple threads.
>
> Maybe you're right, but I haven't found examples. A pointer would be
> appreciated. Am I correct assuming that by default there is only one
> thread in the server process, and if multiple threads are trying to
> access the proxy, all but one will be blocked?
>
>> In your case, though, it sounds like you only want to vend one object 
>> through which all your clients communicate. Even if that communication is 
>> achieved by asking the vended object for another object with which to 
>> communicate.
>
> I don't mind to vend only a single object, through which to ask for
> the other object to actually communicate with clients. I've been
> thinking about it myself. The problem is how to spawn a new thread for
> each such object in the server process and make it listen to all
> incoming requests from the corresponding client.
>
> Thanks,
>
> Oleg.
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Efficiently adding a bunch of items to an NSMutableArray

2010-09-22 Thread Oleg Krupnov
Hi,

I have a NSMutableArray and need to add a number of elements to it,
and their quantity I know in advance (in fact, they come from another
array).

I think that if I add them one-by-one in a loop, the array will have
to reallocate its internal memory frequently. This seems inefficient.

I'd like to avoid this and instead have the array to re-allocate its
memory only once to increment the capacity by the known value.

I could use "arrayWithCapacity" creation method, but the array already
exists. It seems that the -addObjectsFromArray: method may be what I
need, but the docs do not make it clear if it's internally optimized
to do only a single memory re-allocation. Have anyone tested this?

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Accessing NSDistantObject from different threads concurrently

2010-09-20 Thread Oleg Krupnov
Thanks, Kyle

> Multithreading is not a prerequisite for serving multiple clients. Depending 
> on what your server's doing, sticking with NSRunLoop-based multiplexing might 
> be a lot easier.

The server's job is associated with slow devices, such as disk, but
are quite lengthy in time. In your scenario, all client threads will
be unnecessarily waiting for the server to complete the current job,
while there is still a lot of CPU time to run the other jobs
concurrently.

> The NSConnection documentation has a bunch of methods for dealing with 
> multiple threads.

Maybe you're right, but I haven't found examples. A pointer would be
appreciated. Am I correct assuming that by default there is only one
thread in the server process, and if multiple threads are trying to
access the proxy, all but one will be blocked?

> In your case, though, it sounds like you only want to vend one object through 
> which all your clients communicate. Even if that communication is achieved by 
> asking the vended object for another object with which to communicate.

I don't mind to vend only a single object, through which to ask for
the other object to actually communicate with clients. I've been
thinking about it myself. The problem is how to spawn a new thread for
each such object in the server process and make it listen to all
incoming requests from the corresponding client.

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Accessing NSDistantObject from different threads concurrently

2010-09-20 Thread Oleg Krupnov
Hi,

I have a main process and an auxiliary process that vends
NSDistantObject to do some job for the main process upon request. In
other words, the main process is a client, and the auxiliary process
is a server. I have been able to implement this when there is only one
thread in the client process.

Now I need to have multiple threads in the client process. Each client
thread must run concurrently with other client threads, so that if two
or more client threads request the server process at the same time,
they should not block waiting for each other. In other words, the
server should probably create a thread for each client thread.

What is the best way to do this? It's not clear how to vend multiple
NSDistantObjects for multiple client threads, and spawning multiple
auxiliary processes for each client thread would be a nightmare...

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


How to grab content of CALayer and sublayers into a bitmap

2010-07-21 Thread Oleg Krupnov
Hi,

I need to make a snapshot of a CALayer, together with all its
sublayers and effects, into a bitmap.

I've found I can use -[CALayer renderInContext:], but I find it too
slow, particularly because some of the sublayers have shadows and the
Shark shows that most of time is spent in calculating blur
convolutions of the shadows.

On the other hand, all those shadows are already rendered to the
screen, so theoretically there is no need to render them again.

Is there a way I could directly grab what I see in the layer into a bitmap?

What I have already tried:
-[NSBitmapImageRep initWithFocusedViewRect:] -- doesn't work, shows
empty box instead of the layer-hosting view

- [NSView cacheDisplayInRect:] -- does not work unless you put
-[CALayer renderInContext:] into the layer-hosting view's -drawRect:,
so see the problem above

The content of layers is drawn using -[CALayer drawLayer:inContext:]

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Flipping coordinate system of a CALayer

2010-07-21 Thread Oleg Krupnov
Responding to myself, as I promised. I have found a fatal problem with
my approach on Leopard. The layers begin to appear in weird places,
sometimes they disappear at all. As it turns out, -setPosition: is
called with wrong values (probably assuming a different anchorPoint)
and -setBounds: is called with negative height and negative origin.y.
I tried to fix this by also overriding -setPosition: and -setBounds:,
but the problems seem to only spawn more, because the system seem to
internally assume certain values of bounds, anchorPoint, position etc.
after it sets them, so that when they appear to be different because
of the overriden setters, the effect can be a total mess.

I feel I have to abandon the idea of flipping layer geometry
altogether, because if it even doesn't work on Leopard, then the very
purpose of the thing is defeated. If I could drop support of Leopard,
I could use the geometryFlipped without any problem.

I feel very upset that there is no easy way to use the top-left-origin
coordinate system in Core Animation on Leopard. It's beyond my
understanding how it could escape from the creators of Core Animation,
that having the origin in the top left corner is the most natural
thing for computer screens. All scrolling, text flow etc. always start
from the top, not from the bottom. I always find myself fighting with
"flipped" coordinate systems and I have never encountered a single
case when having the origin at the bottom would be helpful. Sigh :(



On Fri, Jul 16, 2010 at 11:48 AM, Oleg Krupnov  wrote:
> Further investigation has shown that when the custom layer-hosting
> view is placed in the parent layer-backed container view, the parent
> view internally discards the flipping transform of the child view's
> root layer on each call to its -setFrame (which can be quite often).
>
> I have cured this problem by subclassing CALayer of the root layer of
> the custom layer-hosting view and overriding its following methods:
>
> - (void)setTransform:(CATransform3D)m
> {
>        CATransform3D flipTransform = CATransform3DIdentity;
>        flipTransform.m22 = -1.0;
>        [super setTransform:flipTransform];
> }
>
> - (void)setAnchorPoint:(CGPoint)point
> {
>        [super setAnchorPoint:CGPointMake(0.0, 1.0)];
> }
>
> This seems to work pretty well so far. If I come up with any problem,
> I'll post it here.
>
> And also it doesn't seem like a bad hack (unlike calling private
> methods). What do you think?
>
>
> Thanks,
>
> On Fri, Jul 16, 2010 at 7:01 AM, Scott Anguish  wrote:
>>
>> On Jul 15, 2010, at 1:24 PM, Kyle Sluder wrote:
>>
>>> On Thu, Jul 15, 2010 at 9:18 AM, Oleg Krupnov  
>>> wrote:
>>>> Is this a bug? And how to work around it?
>>>
>>> There are lots of bugs with flipped layer-hosting views inside of
>>> layer-backed views.. See this thread:
>>> http://lists.apple.com/archives/cocoa-dev/2010/May/msg00988.html
>>>
>>> The only workaround I was able to get working was to call a private
>>> AppKit method to fix up the layer geometry.
>>>
>>
>> Which is a no-no, and shouldn’t be done. Bad Kyle. No biscuit.
>>
>>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Animate NSWindow frame using Core Animation?

2010-07-16 Thread Oleg Krupnov
My "table" view is layer-hosting.

The contentView of my window is layer-backed.

I even tried to setWantsLayer:YES for the superview of the
contentView, that is, the theme frame view of the window, but it does
not seem to bring Core Animation into the window frame animation.



On Fri, Jul 16, 2010 at 2:38 PM, vincent habchi  wrote:
> Le 16 juil. 2010 à 12:38, Oleg Krupnov a écrit :
>
>> Any other ideas?
>
> Is your view CALayer backed?
> Vincent
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Animate NSWindow frame using Core Animation?

2010-07-16 Thread Oleg Krupnov
Thanks Mike,

I forgot to mention that I've already tried -[NSWindow
setFrame:display:animate:], but it does not seem to differ from the
other methods I mentioned.

Well, it's all quite smooth, but very noticeably less smooth than the
Core Animation-powered animations of the views inside the window.
Since I want some of the view animations and window animations happen
at the same time, this difference becomes very noticeable.

For example, consider such case: my window displays a vertical table
of items, and when a new item is added with an animation to the table,
the window should also grow vertically with animation to give room for
the new item. The view is added so smoothly and the window grows so
jaggedly...

Any other ideas?


On Fri, Jul 16, 2010 at 1:28 PM, Mike Abdullah
 wrote:
> Aside from Core Animation, you could also try -setFrame:display:animate:
>
> It blocks the main thread while running, but is generally pretty smooth.
>
> On 16 Jul 2010, at 10:55, Oleg Krupnov wrote:
>
>> Hi,
>>
>> I'm using quite a few animations in my app's UI, using the Core
>> Animation, and all of the animations work wonderfully smooth and
>> quick.
>>
>> However, when I need to animate the frame of the window (namely,
>> change its size), it feels so sluggish and jagged.
>>
>> I guess this is because, unlike the views inside the window, the
>> window itself is not using Core Animation under the hood, but some
>> "usual" Quartz drawing.
>>
>> So the question is, is there a way to make the NSWindow also use Core
>> Animation when animating the change of its size or position?
>>
>> So far I have tried NSViewAnimation, [NSWindow animator] proxy and
>> even explicitly added CAAnimations to the proxy, but it all seems to
>> result in the same sluggish animation.
>>
>> Thanks,
>>
>> Oleg.
>> ___
>>
>> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
>>
>> Please do not post admin requests or moderator comments to the list.
>> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>>
>> Help/Unsubscribe/Update your Subscription:
>> http://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40mikeabdullah.net
>>
>> This email sent to cocoa...@mikeabdullah.net
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Animate NSWindow frame using Core Animation?

2010-07-16 Thread Oleg Krupnov
Hi,

I'm using quite a few animations in my app's UI, using the Core
Animation, and all of the animations work wonderfully smooth and
quick.

However, when I need to animate the frame of the window (namely,
change its size), it feels so sluggish and jagged.

I guess this is because, unlike the views inside the window, the
window itself is not using Core Animation under the hood, but some
"usual" Quartz drawing.

So the question is, is there a way to make the NSWindow also use Core
Animation when animating the change of its size or position?

So far I have tried NSViewAnimation, [NSWindow animator] proxy and
even explicitly added CAAnimations to the proxy, but it all seems to
result in the same sluggish animation.

Thanks,

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Flipping coordinate system of a CALayer

2010-07-16 Thread Oleg Krupnov
Further investigation has shown that when the custom layer-hosting
view is placed in the parent layer-backed container view, the parent
view internally discards the flipping transform of the child view's
root layer on each call to its -setFrame (which can be quite often).

I have cured this problem by subclassing CALayer of the root layer of
the custom layer-hosting view and overriding its following methods:

- (void)setTransform:(CATransform3D)m
{
CATransform3D flipTransform = CATransform3DIdentity;
flipTransform.m22 = -1.0;
[super setTransform:flipTransform];
}

- (void)setAnchorPoint:(CGPoint)point
{
[super setAnchorPoint:CGPointMake(0.0, 1.0)];
}

This seems to work pretty well so far. If I come up with any problem,
I'll post it here.

And also it doesn't seem like a bad hack (unlike calling private
methods). What do you think?


Thanks,

On Fri, Jul 16, 2010 at 7:01 AM, Scott Anguish  wrote:
>
> On Jul 15, 2010, at 1:24 PM, Kyle Sluder wrote:
>
>> On Thu, Jul 15, 2010 at 9:18 AM, Oleg Krupnov  wrote:
>>> Is this a bug? And how to work around it?
>>
>> There are lots of bugs with flipped layer-hosting views inside of
>> layer-backed views.. See this thread:
>> http://lists.apple.com/archives/cocoa-dev/2010/May/msg00988.html
>>
>> The only workaround I was able to get working was to call a private
>> AppKit method to fix up the layer geometry.
>>
>
> Which is a no-no, and shouldn’t be done. Bad Kyle. No biscuit.
>
>
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Flipping coordinate system of a CALayer

2010-07-15 Thread Oleg Krupnov
Hi,

In a layer-hosting custom view, I'm flipping the root layer coordinate
system with the following code:

CGAffineTransform flipTransform;
flipTransform.a = 1.0;
flipTransform.b = 0.0;
flipTransform.c = 0.0;
flipTransform.d = -1.0;
flipTransform.tx = 0.0;
flipTransform.ty = 0.0;
[rootLayer setAffineTransform:flipTransform];

This code works fine and causes the layer and all its sublayers to
flip so that the origin is in the top left corner.


However, the problem is that when I place this custom view inside
another layer-backed view (or just check the "Wants Core Animation
Layer" box of the parent view in Interface builder), I observe that
the coordinate system of the layer is unflipped, like if the code
above did not have any effect.

Is this a bug? And how to work around it?

I could use the 10.6's geometryFlipped property, which is free of this
problem, but I'd still like to support 10.5.

Thanks!

Oleg.
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


  1   2   3   >