diff --git a/extras/audio plugins/wrapper/RTAS/juce_RTAS_MacUtilities.mm b/extras/audio plugins/wrapper/RTAS/juce_RTAS_MacUtilities.mm index 81930bc53f..8ececa2fee 100644 --- a/extras/audio plugins/wrapper/RTAS/juce_RTAS_MacUtilities.mm +++ b/extras/audio plugins/wrapper/RTAS/juce_RTAS_MacUtilities.mm @@ -114,18 +114,21 @@ void removeSubWindow (void* nsWindow, Component* comp) [hostWindow release]; } -static bool isJuceWindow (WindowRef w) +namespace { - for (int i = ComponentPeer::getNumPeers(); --i >= 0;) + bool isJuceWindow (WindowRef w) { - ComponentPeer* peer = ComponentPeer::getPeer(i); - NSView* view = (NSView*) peer->getNativeHandle(); + for (int i = ComponentPeer::getNumPeers(); --i >= 0;) + { + ComponentPeer* peer = ComponentPeer::getPeer(i); + NSView* view = (NSView*) peer->getNativeHandle(); - if ([[view window] windowRef] == w) - return true; + if ([[view window] windowRef] == w) + return true; + } + + return false; } - - return false; } void forwardCurrentKeyEventToHostWindow() diff --git a/extras/audio plugins/wrapper/RTAS/juce_RTAS_WinUtilities.cpp b/extras/audio plugins/wrapper/RTAS/juce_RTAS_WinUtilities.cpp index 8647585256..c234836a19 100644 --- a/extras/audio plugins/wrapper/RTAS/juce_RTAS_WinUtilities.cpp +++ b/extras/audio plugins/wrapper/RTAS/juce_RTAS_WinUtilities.cpp @@ -85,46 +85,49 @@ void JUCE_CALLTYPE resizeHostWindow (void* hostWindow, #if ! JucePlugin_EditorRequiresKeyboardFocus -static HWND findMDIParentOf (HWND w) +namespace { - const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME); - - while (w != 0) + HWND findMDIParentOf (HWND w) { - HWND parent = GetParent (w); + const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME); - if (parent == 0) - break; - - TCHAR windowType [32]; - zeromem (windowType, sizeof (windowType)); - GetClassName (parent, windowType, 31); - - if (String (windowType).equalsIgnoreCase ("MDIClient")) + while (w != 0) { + HWND parent = GetParent (w); + + if (parent == 0) + break; + + TCHAR windowType [32]; + zeromem (windowType, sizeof (windowType)); + GetClassName (parent, windowType, 31); + + if (String (windowType).equalsIgnoreCase ("MDIClient")) + { + w = parent; + break; + } + + RECT windowPos; + GetWindowRect (w, &windowPos); + + RECT parentPos; + GetWindowRect (parent, &parentPos); + + int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left); + int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top); + + if (dw > 100 || dh > 100) + break; + w = parent; - break; + + if (dw == 2 * frameThickness) + break; } - RECT windowPos; - GetWindowRect (w, &windowPos); - - RECT parentPos; - GetWindowRect (parent, &parentPos); - - int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left); - int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top); - - if (dw > 100 || dh > 100) - break; - - w = parent; - - if (dw == 2 * frameThickness) - break; + return w; } - - return w; } void JUCE_CALLTYPE passFocusToHostWindow (void* hostWindow) diff --git a/extras/audio plugins/wrapper/RTAS/juce_RTAS_Wrapper.cpp b/extras/audio plugins/wrapper/RTAS/juce_RTAS_Wrapper.cpp index cf0fdf1979..ea360eb0ad 100644 --- a/extras/audio plugins/wrapper/RTAS/juce_RTAS_Wrapper.cpp +++ b/extras/audio plugins/wrapper/RTAS/juce_RTAS_Wrapper.cpp @@ -131,22 +131,9 @@ static const int bypassControlIndex = 1; */ extern AudioProcessor* JUCE_CALLTYPE createPluginFilter(); - -//============================================================================== -static float longToFloat (const long n) throw() -{ - return (float) ((((double) n) + (double) 0x80000000) / (double) 0xffffffff); -} - -static long floatToLong (const float n) throw() -{ - return roundToInt (jlimit (-(double) 0x80000000, - (double) 0x7fffffff, - n * (double) 0xffffffff - (double) 0x80000000)); -} - static int numInstances = 0; + //============================================================================== class JucePlugInProcess : public CEffectProcessMIDI, public CEffectProcessRTAS, @@ -836,6 +823,17 @@ private: bool prepared; double sampleRate; + static float longToFloat (const long n) throw() + { + return (float) ((((double) n) + (double) 0x80000000) / (double) 0xffffffff); + } + + static long floatToLong (const float n) throw() + { + return roundToInt (jlimit (-(double) 0x80000000, (double) 0x7fffffff, + n * (double) 0xffffffff - (double) 0x80000000)); + } + void bypassBuffers (float** const inputs, float** const outputs, const long numSamples) const { for (int i = fNumOutputs; --i >= 0;) diff --git a/extras/audio plugins/wrapper/VST/juce_VST_Wrapper.cpp b/extras/audio plugins/wrapper/VST/juce_VST_Wrapper.cpp index d3600a17e1..d1d53f760b 100644 --- a/extras/audio plugins/wrapper/VST/juce_VST_Wrapper.cpp +++ b/extras/audio plugins/wrapper/VST/juce_VST_Wrapper.cpp @@ -167,46 +167,49 @@ END_JUCE_NAMESPACE //============================================================================== #if JUCE_WINDOWS -static HWND findMDIParentOf (HWND w) +namespace { - const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME); - - while (w != 0) + HWND findMDIParentOf (HWND w) { - HWND parent = GetParent (w); + const int frameThickness = GetSystemMetrics (SM_CYFIXEDFRAME); - if (parent == 0) - break; - - TCHAR windowType [32]; - zeromem (windowType, sizeof (windowType)); - GetClassName (parent, windowType, 31); - - if (String (windowType).equalsIgnoreCase ("MDIClient")) + while (w != 0) { + HWND parent = GetParent (w); + + if (parent == 0) + break; + + TCHAR windowType [32]; + zeromem (windowType, sizeof (windowType)); + GetClassName (parent, windowType, 31); + + if (String (windowType).equalsIgnoreCase ("MDIClient")) + { + w = parent; + break; + } + + RECT windowPos; + GetWindowRect (w, &windowPos); + + RECT parentPos; + GetWindowRect (parent, &parentPos); + + const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left); + const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top); + + if (dw > 100 || dh > 100) + break; + w = parent; - break; + + if (dw == 2 * frameThickness) + break; } - RECT windowPos; - GetWindowRect (w, &windowPos); - - RECT parentPos; - GetWindowRect (parent, &parentPos); - - const int dw = (parentPos.right - parentPos.left) - (windowPos.right - windowPos.left); - const int dh = (parentPos.bottom - parentPos.top) - (windowPos.bottom - windowPos.top); - - if (dw > 100 || dh > 100) - break; - - w = parent; - - if (dw == 2 * frameThickness) - break; + return w; } - - return w; } //============================================================================== @@ -1473,31 +1476,33 @@ extern AudioProcessor* JUCE_CALLTYPE createPluginFilter(); //============================================================================== -static AEffect* pluginEntryPoint (audioMasterCallback audioMaster) +namespace { - JUCE_AUTORELEASEPOOL - initialiseJuce_GUI(); - - try + AEffect* pluginEntryPoint (audioMasterCallback audioMaster) { - if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0) - { - AudioProcessor* const filter = createPluginFilter(); + JUCE_AUTORELEASEPOOL + initialiseJuce_GUI(); - if (filter != 0) + try + { + if (audioMaster (0, audioMasterVersion, 0, 0, 0, 0) != 0) { - JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter); - return wrapper->getAeffect(); + AudioProcessor* const filter = createPluginFilter(); + + if (filter != 0) + { + JuceVSTWrapper* const wrapper = new JuceVSTWrapper (audioMaster, filter); + return wrapper->getAeffect(); + } } } + catch (...) + {} + + return 0; } - catch (...) - {} - - return 0; } - //============================================================================== // Mac startup code.. #if JUCE_MAC diff --git a/src/audio/audio_file_formats/juce_WavAudioFormat.cpp b/src/audio/audio_file_formats/juce_WavAudioFormat.cpp index 227e5a3665..6df172a9f2 100644 --- a/src/audio/audio_file_formats/juce_WavAudioFormat.cpp +++ b/src/audio/audio_file_formats/juce_WavAudioFormat.cpp @@ -632,37 +632,40 @@ AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, return 0; } -static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata) +namespace { - TemporaryFile tempFile (file); - - WavAudioFormat wav; - ScopedPointer reader (wav.createReaderFor (file.createInputStream(), true)); - - if (reader != 0) + bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata) { - ScopedPointer outStream (tempFile.getFile().createOutputStream()); + TemporaryFile tempFile (file); - if (outStream != 0) + WavAudioFormat wav; + ScopedPointer reader (wav.createReaderFor (file.createInputStream(), true)); + + if (reader != 0) { - ScopedPointer writer (wav.createWriterFor (outStream, reader->sampleRate, - reader->numChannels, reader->bitsPerSample, - metadata, 0)); + ScopedPointer outStream (tempFile.getFile().createOutputStream()); - if (writer != 0) + if (outStream != 0) { - outStream.release(); + ScopedPointer writer (wav.createWriterFor (outStream, reader->sampleRate, + reader->numChannels, reader->bitsPerSample, + metadata, 0)); - bool ok = writer->writeFromAudioReader (*reader, 0, -1); - writer = 0; - reader = 0; + if (writer != 0) + { + outStream.release(); - return ok && tempFile.overwriteTargetFileWithTemporary(); + bool ok = writer->writeFromAudioReader (*reader, 0, -1); + writer = 0; + reader = 0; + + return ok && tempFile.overwriteTargetFileWithTemporary(); + } } } - } - return false; + return false; + } } bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata) diff --git a/src/audio/midi/juce_MidiBuffer.cpp b/src/audio/midi/juce_MidiBuffer.cpp index 2f53813d32..4dad307c0e 100644 --- a/src/audio/midi/juce_MidiBuffer.cpp +++ b/src/audio/midi/juce_MidiBuffer.cpp @@ -112,38 +112,41 @@ void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber) addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber); } -static int findActualEventLength (const uint8* const data, const int maxBytes) throw() +namespace MidiBufferHelpers { - unsigned int byte = (unsigned int) *data; - int size = 0; - - if (byte == 0xf0 || byte == 0xf7) + int findActualEventLength (const uint8* const data, const int maxBytes) throw() { - const uint8* d = data + 1; + unsigned int byte = (unsigned int) *data; + int size = 0; - while (d < data + maxBytes) - if (*d++ == 0xf7) - break; + if (byte == 0xf0 || byte == 0xf7) + { + const uint8* d = data + 1; - size = (int) (d - data); - } - else if (byte == 0xff) - { - int n; - const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n); - size = jmin (maxBytes, n + 2 + bytesLeft); - } - else if (byte >= 0x80) - { - size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte)); - } + while (d < data + maxBytes) + if (*d++ == 0xf7) + break; - return size; + size = (int) (d - data); + } + else if (byte == 0xff) + { + int n; + const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n); + size = jmin (maxBytes, n + 2 + bytesLeft); + } + else if (byte >= 0x80) + { + size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte)); + } + + return size; + } } void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber) { - const int numBytes = findActualEventLength (static_cast (newData), maxBytes); + const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast (newData), maxBytes); if (numBytes > 0) { diff --git a/src/audio/plugins/formats/juce_VSTPluginFormat.cpp b/src/audio/plugins/formats/juce_VSTPluginFormat.cpp index a1c9ab45d0..40369ed9ea 100644 --- a/src/audio/plugins/formats/juce_VSTPluginFormat.cpp +++ b/src/audio/plugins/formats/juce_VSTPluginFormat.cpp @@ -172,40 +172,43 @@ struct fxProgramSet char chunk[8]; // variable }; -static long vst_swap (const long x) throw() +namespace { - #ifdef JUCE_LITTLE_ENDIAN - return (long) ByteOrder::swap ((uint32) x); - #else - return x; - #endif -} + long vst_swap (const long x) throw() + { + #ifdef JUCE_LITTLE_ENDIAN + return (long) ByteOrder::swap ((uint32) x); + #else + return x; + #endif + } -static float vst_swapFloat (const float x) throw() -{ - #ifdef JUCE_LITTLE_ENDIAN - union { uint32 asInt; float asFloat; } n; - n.asFloat = x; - n.asInt = ByteOrder::swap (n.asInt); - return n.asFloat; - #else - return x; - #endif -} + float vst_swapFloat (const float x) throw() + { + #ifdef JUCE_LITTLE_ENDIAN + union { uint32 asInt; float asFloat; } n; + n.asFloat = x; + n.asInt = ByteOrder::swap (n.asInt); + return n.asFloat; + #else + return x; + #endif + } -static double getVSTHostTimeNanoseconds() -{ - #if JUCE_WINDOWS - return timeGetTime() * 1000000.0; - #elif JUCE_LINUX - timeval micro; - gettimeofday (µ, 0); - return micro.tv_usec * 1000.0; - #elif JUCE_MAC - UnsignedWide micro; - Microseconds (µ); - return micro.lo * 1000.0; - #endif + double getVSTHostTimeNanoseconds() + { + #if JUCE_WINDOWS + return timeGetTime() * 1000000.0; + #elif JUCE_LINUX + timeval micro; + gettimeofday (µ, 0); + return micro.tv_usec * 1000.0; + #elif JUCE_MAC + UnsignedWide micro; + Microseconds (µ); + return micro.lo * 1000.0; + #endif + } } //============================================================================== @@ -253,94 +256,97 @@ typedef void (*EventProcPtr) (XEvent* ev); static bool xErrorTriggered; -static int temporaryErrorHandler (Display*, XErrorEvent*) +namespace { - xErrorTriggered = true; - return 0; -} - -static int getPropertyFromXWindow (Window handle, Atom atom) -{ - XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler); - xErrorTriggered = false; - - int userSize; - unsigned long bytes, userCount; - unsigned char* data; - Atom userType; - - XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType, - &userType, &userSize, &userCount, &bytes, &data); - - XSetErrorHandler (oldErrorHandler); - - return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast (data) - : 0; -} - -static Window getChildWindow (Window windowToCheck) -{ - Window rootWindow, parentWindow; - Window* childWindows; - unsigned int numChildren; - - XQueryTree (display, - windowToCheck, - &rootWindow, - &parentWindow, - &childWindows, - &numChildren); - - if (numChildren > 0) - return childWindows [0]; - - return 0; -} - -static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw() -{ - if (e.mods.isLeftButtonDown()) + int temporaryErrorHandler (Display*, XErrorEvent*) { - ev.xbutton.button = Button1; - ev.xbutton.state |= Button1Mask; + xErrorTriggered = true; + return 0; } - else if (e.mods.isRightButtonDown()) - { - ev.xbutton.button = Button3; - ev.xbutton.state |= Button3Mask; - } - else if (e.mods.isMiddleButtonDown()) - { - ev.xbutton.button = Button2; - ev.xbutton.state |= Button2Mask; - } -} -static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw() -{ - if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask; - else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask; - else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask; -} - -static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw() -{ - if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask; - else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask; - else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask; -} - -static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw() -{ - if (increment < 0) + int getPropertyFromXWindow (Window handle, Atom atom) { - ev.xbutton.button = Button5; - ev.xbutton.state |= Button5Mask; + XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler); + xErrorTriggered = false; + + int userSize; + unsigned long bytes, userCount; + unsigned char* data; + Atom userType; + + XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType, + &userType, &userSize, &userCount, &bytes, &data); + + XSetErrorHandler (oldErrorHandler); + + return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast (data) + : 0; } - else if (increment > 0) + + Window getChildWindow (Window windowToCheck) { - ev.xbutton.button = Button4; - ev.xbutton.state |= Button4Mask; + Window rootWindow, parentWindow; + Window* childWindows; + unsigned int numChildren; + + XQueryTree (display, + windowToCheck, + &rootWindow, + &parentWindow, + &childWindows, + &numChildren); + + if (numChildren > 0) + return childWindows [0]; + + return 0; + } + + void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw() + { + if (e.mods.isLeftButtonDown()) + { + ev.xbutton.button = Button1; + ev.xbutton.state |= Button1Mask; + } + else if (e.mods.isRightButtonDown()) + { + ev.xbutton.button = Button3; + ev.xbutton.state |= Button3Mask; + } + else if (e.mods.isMiddleButtonDown()) + { + ev.xbutton.button = Button2; + ev.xbutton.state |= Button2Mask; + } + } + + void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw() + { + if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask; + else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask; + else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask; + } + + void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw() + { + if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask; + else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask; + else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask; + } + + void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw() + { + if (increment < 0) + { + ev.xbutton.button = Button5; + ev.xbutton.state |= Button5Mask; + } + else if (increment > 0) + { + ev.xbutton.button = Button4; + ev.xbutton.state |= Button4Mask; + } } } @@ -2184,66 +2190,67 @@ int VSTPluginInstance::dispatch (const int opcode, const int index, const int va } //============================================================================== -// handles non plugin-specific callbacks.. - -static const int defaultVSTSampleRateValue = 16384; -static const int defaultVSTBlockSizeValue = 512; - - -static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt) +namespace { - (void) index; - (void) value; - (void) opt; + static const int defaultVSTSampleRateValue = 16384; + static const int defaultVSTBlockSizeValue = 512; - switch (opcode) + // handles non plugin-specific callbacks.. + VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt) { - case audioMasterCanDo: + (void) index; + (void) value; + (void) opt; + + switch (opcode) { - static const char* canDos[] = { "supplyIdle", - "sendVstEvents", - "sendVstMidiEvent", - "sendVstTimeInfo", - "receiveVstEvents", - "receiveVstMidiEvent", - "supportShell", - "shellCategory" }; + case audioMasterCanDo: + { + static const char* canDos[] = { "supplyIdle", + "sendVstEvents", + "sendVstMidiEvent", + "sendVstTimeInfo", + "receiveVstEvents", + "receiveVstMidiEvent", + "supportShell", + "shellCategory" }; - for (int i = 0; i < numElementsInArray (canDos); ++i) - if (strcmp (canDos[i], (const char*) ptr) == 0) - return 1; + for (int i = 0; i < numElementsInArray (canDos); ++i) + if (strcmp (canDos[i], (const char*) ptr) == 0) + return 1; - return 0; + return 0; + } + + case audioMasterVersion: return 0x2400; + case audioMasterCurrentId: return shellUIDToCreate; + case audioMasterGetNumAutomatableParameters: return 0; + case audioMasterGetAutomationState: return 1; + case audioMasterGetVendorVersion: return 0x0101; + + case audioMasterGetVendorString: + case audioMasterGetProductString: + { + String hostName ("Juce VST Host"); + + if (JUCEApplication::getInstance() != 0) + hostName = JUCEApplication::getInstance()->getApplicationName(); + + hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1); + break; + } + + case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue; + case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue; + case audioMasterSetOutputSampleRate: return 0; + + default: + DBG ("*** Unhandled VST Callback: " + String ((int) opcode)); + break; } - case audioMasterVersion: return 0x2400; - case audioMasterCurrentId: return shellUIDToCreate; - case audioMasterGetNumAutomatableParameters: return 0; - case audioMasterGetAutomationState: return 1; - case audioMasterGetVendorVersion: return 0x0101; - - case audioMasterGetVendorString: - case audioMasterGetProductString: - { - String hostName ("Juce VST Host"); - - if (JUCEApplication::getInstance() != 0) - hostName = JUCEApplication::getInstance()->getApplicationName(); - - hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1); - break; - } - - case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue; - case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue; - case audioMasterSetOutputSampleRate: return 0; - - default: - DBG ("*** Unhandled VST Callback: " + String ((int) opcode)); - break; + return 0; } - - return 0; } // handles callbacks for a specific plugin diff --git a/src/audio/plugins/juce_KnownPluginList.cpp b/src/audio/plugins/juce_KnownPluginList.cpp index dab0c37f94..6338e2f127 100644 --- a/src/audio/plugins/juce_KnownPluginList.cpp +++ b/src/audio/plugins/juce_KnownPluginList.cpp @@ -93,17 +93,20 @@ void KnownPluginList::removeType (const int index) sendChangeMessage (this); } -static const Time getPluginFileModTime (const String& fileOrIdentifier) +namespace { - if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':') - return File (fileOrIdentifier).getLastModificationTime(); + const Time getPluginFileModTime (const String& fileOrIdentifier) + { + if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':') + return File (fileOrIdentifier).getLastModificationTime(); - return Time (0); -} + return Time (0); + } -static bool timesAreDifferent (const Time& t1, const Time& t2) throw() -{ - return t1 != t2 || t1 == Time (0); + bool timesAreDifferent (const Time& t1, const Time& t2) throw() + { + return t1 != t2 || t1 == Time (0); + } } bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const diff --git a/src/containers/juce_DynamicObject.cpp b/src/containers/juce_DynamicObject.cpp index 497379e559..3906edc12d 100644 --- a/src/containers/juce_DynamicObject.cpp +++ b/src/containers/juce_DynamicObject.cpp @@ -41,7 +41,7 @@ DynamicObject::~DynamicObject() bool DynamicObject::hasProperty (const Identifier& propertyName) const { - var* const v = properties.getItem (propertyName); + var* const v = properties.getVarPointer (propertyName); return v != 0 && ! v->isMethod(); } diff --git a/src/containers/juce_NamedValueSet.cpp b/src/containers/juce_NamedValueSet.cpp index c8bbedde1d..e12f432241 100644 --- a/src/containers/juce_NamedValueSet.cpp +++ b/src/containers/juce_NamedValueSet.cpp @@ -95,11 +95,11 @@ const var& NamedValueSet::operator[] (const Identifier& name) const const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const { - const var* v = getItem (name); + const var* v = getVarPointer (name); return v != 0 ? *v : defaultReturnValue; } -var* NamedValueSet::getItem (const Identifier& name) const +var* NamedValueSet::getVarPointer (const Identifier& name) const { for (int i = values.size(); --i >= 0;) { @@ -134,7 +134,7 @@ bool NamedValueSet::set (const Identifier& name, const var& newValue) bool NamedValueSet::contains (const Identifier& name) const { - return getItem (name) != 0; + return getVarPointer (name) != 0; } bool NamedValueSet::remove (const Identifier& name) diff --git a/src/containers/juce_NamedValueSet.h b/src/containers/juce_NamedValueSet.h index 51651a21ef..411d85b135 100644 --- a/src/containers/juce_NamedValueSet.h +++ b/src/containers/juce_NamedValueSet.h @@ -69,13 +69,9 @@ public: */ const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const; - /** Returns a pointer to the object holding a named value, or - null if there is no value with this name. */ - var* getItem (const Identifier& name) const; - /** Changes or adds a named value. - @returns true if a value was changed or added; false if the - value was already set the the value passed-in. + @returns true if a value was changed or added; false if the + value was already set the the value passed-in. */ bool set (const Identifier& name, const var& newValue); @@ -103,6 +99,15 @@ public: /** Removes all values. */ void clear(); + //============================================================================== + /** Returns a pointer to the var that holds a named value, or null if there is + no value with this name. + + Do not use this method unless you really need access to the internal var object + for some reason - for normal reading and writing always prefer operator[]() and set(). + */ + var* getVarPointer (const Identifier& name) const; + //============================================================================== juce_UseDebuggingNewOperator diff --git a/src/containers/juce_ValueTree.cpp b/src/containers/juce_ValueTree.cpp index 6607b7b9f6..84323cbae9 100644 --- a/src/containers/juce_ValueTree.cpp +++ b/src/containers/juce_ValueTree.cpp @@ -321,7 +321,7 @@ void ValueTree::SharedObject::setProperty (const Identifier& name, const var& ne } else { - var* const existingValue = properties.getItem (name); + var* const existingValue = properties.getVarPointer (name); if (existingValue != 0) { diff --git a/src/core/juce_Initialisation.cpp b/src/core/juce_Initialisation.cpp index 0f047be1ba..b969c5b9b4 100644 --- a/src/core/juce_Initialisation.cpp +++ b/src/core/juce_Initialisation.cpp @@ -126,11 +126,12 @@ JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI() // turn RTTI off.. try { - TextButton tb (String::empty); - Component* c = &tb; + MemoryOutputStream mo; + OutputStream* o = &mo; // Got an exception here? Then TURN ON RTTI in your compiler settings!! - c = dynamic_cast (c); + o = dynamic_cast (o); + jassert (o != 0); } catch (...) { diff --git a/src/gui/components/code_editor/juce_CodeDocument.cpp b/src/gui/components/code_editor/juce_CodeDocument.cpp index 4977a0ceb4..72ce156129 100644 --- a/src/gui/components/code_editor/juce_CodeDocument.cpp +++ b/src/gui/components/code_editor/juce_CodeDocument.cpp @@ -604,10 +604,13 @@ bool CodeDocument::hasChangedSinceSavePoint() const throw() } //============================================================================== -static int getCodeCharacterCategory (const juce_wchar character) throw() +namespace CodeDocumentHelpers { - return (CharacterFunctions::isLetterOrDigit (character) || character == '_') - ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1); + int getCharacterType (const juce_wchar character) throw() + { + return (CharacterFunctions::isLetterOrDigit (character) || character == '_') + ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1); + } } const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw() @@ -627,9 +630,9 @@ const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& p if (i == 0) { - const int type = getCodeCharacterCategory (p.getCharacter()); + const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter()); - while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter())) + while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter())) { ++i; p.moveBy (1); @@ -676,9 +679,9 @@ const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& if (i < maxDistance && ! stoppedAtLineStart) { - const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter()); + const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()); - while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter())) + while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter())) { p.moveBy (-1); ++i; diff --git a/src/gui/components/code_editor/juce_CodeEditorComponent.cpp b/src/gui/components/code_editor/juce_CodeEditorComponent.cpp index c98484e558..310ddb511f 100644 --- a/src/gui/components/code_editor/juce_CodeEditorComponent.cpp +++ b/src/gui/components/code_editor/juce_CodeEditorComponent.cpp @@ -778,22 +778,25 @@ void CodeEditorComponent::goToStartOfDocument (const bool selecting) moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting); } -static int findFirstNonWhitespaceChar (const String& line) throw() +namespace CodeEditorHelpers { - const int len = line.length(); + int findFirstNonWhitespaceChar (const String& line) throw() + { + const int len = line.length(); - for (int i = 0; i < len; ++i) - if (! CharacterFunctions::isWhitespace (line [i])) - return i; + for (int i = 0; i < len; ++i) + if (! CharacterFunctions::isWhitespace (line [i])) + return i; - return 0; + return 0; + } } void CodeEditorComponent::goToStartOfLine (const bool selecting) { newTransaction(); - int index = findFirstNonWhitespaceChar (caretPos.getLineText()); + int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText()); if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0) index = 0; diff --git a/src/gui/components/controls/juce_Slider.cpp b/src/gui/components/controls/juce_Slider.cpp index a588b9ddb9..6d2db6b0ee 100644 --- a/src/gui/components/controls/juce_Slider.cpp +++ b/src/gui/components/controls/juce_Slider.cpp @@ -1191,11 +1191,14 @@ void Slider::modifierKeysChanged (const ModifierKeys& modifiers) } } -static double smallestAngleBetween (double a1, double a2) +namespace SliderHelpers { - return jmin (std::abs (a1 - a2), - std::abs (a1 + double_Pi * 2.0 - a2), - std::abs (a2 + double_Pi * 2.0 - a1)); + double smallestAngleBetween (double a1, double a2) throw() + { + return jmin (std::abs (a1 - a2), + std::abs (a1 + double_Pi * 2.0 - a2), + std::abs (a2 + double_Pi * 2.0 - a1)); + } } void Slider::mouseDrag (const MouseEvent& e) @@ -1237,7 +1240,8 @@ void Slider::mouseDrag (const MouseEvent& e) if (angle > rotaryEnd) { - if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd)) + if (SliderHelpers::smallestAngleBetween (angle, rotaryStart) + <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd)) angle = rotaryStart; else angle = rotaryEnd; diff --git a/src/gui/components/filebrowser/juce_FileBrowserComponent.cpp b/src/gui/components/filebrowser/juce_FileBrowserComponent.cpp index 7dd87c2684..8bb0f9f493 100644 --- a/src/gui/components/filebrowser/juce_FileBrowserComponent.cpp +++ b/src/gui/components/filebrowser/juce_FileBrowserComponent.cpp @@ -140,6 +140,7 @@ FileBrowserComponent::FileBrowserComponent (int flags_, FileBrowserComponent::~FileBrowserComponent() { + fileListComponent = 0; fileList = 0; thread.stopThread (10000); } diff --git a/src/gui/components/juce_Component.cpp b/src/gui/components/juce_Component.cpp index 0dec2b816f..aa5ebc3435 100644 --- a/src/gui/components/juce_Component.cpp +++ b/src/gui/components/juce_Component.cpp @@ -1655,17 +1655,20 @@ void Component::sendLookAndFeelChange() } } -static const Identifier getColourPropertyId (const int colourId) +namespace ComponentHelpers { - String s; - s.preallocateStorage (18); - s << "jcclr_" << String::toHexString (colourId); - return s; + const Identifier getColourPropertyId (const int colourId) + { + String s; + s.preallocateStorage (18); + s << "jcclr_" << String::toHexString (colourId); + return s; + } } const Colour Component::findColour (const int colourId, const bool inheritFromParent) const { - var* v = properties.getItem (getColourPropertyId (colourId)); + var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId)); if (v != 0) return Colour ((int) *v); @@ -1678,18 +1681,18 @@ const Colour Component::findColour (const int colourId, const bool inheritFromPa bool Component::isColourSpecified (const int colourId) const { - return properties.contains (getColourPropertyId (colourId)); + return properties.contains (ComponentHelpers::getColourPropertyId (colourId)); } void Component::removeColour (const int colourId) { - if (properties.remove (getColourPropertyId (colourId))) + if (properties.remove (ComponentHelpers::getColourPropertyId (colourId))) colourChanged(); } void Component::setColour (const int colourId, const Colour& colour) { - if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB())) + if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB())) colourChanged(); } diff --git a/src/gui/components/keyboard/juce_KeyboardFocusTraverser.cpp b/src/gui/components/keyboard/juce_KeyboardFocusTraverser.cpp index c45af840ef..8f3ea7eca8 100644 --- a/src/gui/components/keyboard/juce_KeyboardFocusTraverser.cpp +++ b/src/gui/components/keyboard/juce_KeyboardFocusTraverser.cpp @@ -100,39 +100,42 @@ namespace KeyboardFocusHelpers } } -static Component* getIncrementedComponent (Component* const current, const int delta) +namespace KeyboardFocusHelpers { - Component* focusContainer = current->getParentComponent(); - - if (focusContainer != 0) + Component* getIncrementedComponent (Component* const current, const int delta) { - while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer()) - focusContainer = focusContainer->getParentComponent(); + Component* focusContainer = current->getParentComponent(); if (focusContainer != 0) { - Array comps; - KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps); + while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer()) + focusContainer = focusContainer->getParentComponent(); - if (comps.size() > 0) + if (focusContainer != 0) { - const int index = comps.indexOf (current); - return comps [(index + comps.size() + delta) % comps.size()]; + Array comps; + KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps); + + if (comps.size() > 0) + { + const int index = comps.indexOf (current); + return comps [(index + comps.size() + delta) % comps.size()]; + } } } - } - return 0; + return 0; + } } Component* KeyboardFocusTraverser::getNextComponent (Component* current) { - return getIncrementedComponent (current, 1); + return KeyboardFocusHelpers::getIncrementedComponent (current, 1); } Component* KeyboardFocusTraverser::getPreviousComponent (Component* current) { - return getIncrementedComponent (current, -1); + return KeyboardFocusHelpers::getIncrementedComponent (current, -1); } Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent) diff --git a/src/gui/components/layout/juce_MultiDocumentPanel.cpp b/src/gui/components/layout/juce_MultiDocumentPanel.cpp index f818c76c9a..ebfa8a0807 100644 --- a/src/gui/components/layout/juce_MultiDocumentPanel.cpp +++ b/src/gui/components/layout/juce_MultiDocumentPanel.cpp @@ -128,9 +128,12 @@ MultiDocumentPanel::~MultiDocumentPanel() } //============================================================================== -static bool shouldDeleteComp (Component* const c) +namespace MultiDocHelpers { - return c->getProperties() ["mdiDocumentDelete_"]; + bool shouldDeleteComp (Component* const c) + { + return c->getProperties() ["mdiDocumentDelete_"]; + } } bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst) @@ -250,7 +253,7 @@ bool MultiDocumentPanel::closeDocument (Component* component, component->removeComponentListener (this); - const bool shouldDelete = shouldDeleteComp (component); + const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component); component->getProperties().remove ("mdiDocumentDelete_"); component->getProperties().remove ("mdiDocumentBkg_"); @@ -437,7 +440,7 @@ void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode) addDocument (c, Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())), - shouldDeleteComp (c)); + MultiDocHelpers::shouldDeleteComp (c)); } } } diff --git a/src/gui/components/windows/juce_ComponentPeer.cpp b/src/gui/components/windows/juce_ComponentPeer.cpp index 2d5630903b..2d7680a904 100644 --- a/src/gui/components/windows/juce_ComponentPeer.cpp +++ b/src/gui/components/windows/juce_ComponentPeer.cpp @@ -401,21 +401,24 @@ const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw() } //============================================================================== -static FileDragAndDropTarget* findDragAndDropTarget (Component* c, - const StringArray& files, - FileDragAndDropTarget* const lastOne) +namespace ComponentPeerHelpers { - while (c != 0) + FileDragAndDropTarget* findDragAndDropTarget (Component* c, + const StringArray& files, + FileDragAndDropTarget* const lastOne) { - FileDragAndDropTarget* const t = dynamic_cast (c); + while (c != 0) + { + FileDragAndDropTarget* const t = dynamic_cast (c); - if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files))) - return t; + if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files))) + return t; - c = c->getParentComponent(); + c = c->getParentComponent(); + } + + return 0; } - - return 0; } void ComponentPeer::handleFileDragMove (const StringArray& files, const Point& position) @@ -432,7 +435,7 @@ void ComponentPeer::handleFileDragMove (const StringArray& files, const Point -static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h) +namespace { - const int maxVal = 0x3fffffff; + template + bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h) + { + const int maxVal = 0x3fffffff; - return (int) x >= -maxVal && (int) x <= maxVal - && (int) y >= -maxVal && (int) y <= maxVal - && (int) w >= -maxVal && (int) w <= maxVal - && (int) h >= -maxVal && (int) h <= maxVal; + return (int) x >= -maxVal && (int) x <= maxVal + && (int) y >= -maxVal && (int) y <= maxVal + && (int) w >= -maxVal && (int) w <= maxVal + && (int) h >= -maxVal && (int) h <= maxVal; + } } //============================================================================== diff --git a/src/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp b/src/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp index 69b7a7699a..1e9dcd4c14 100644 --- a/src/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp +++ b/src/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.cpp @@ -414,11 +414,14 @@ private: }; //============================================================================== -static forcedinline int safeModulo (int n, const int divisor) throw() +namespace { - jassert (divisor > 0); - n %= divisor; - return (n < 0) ? (n + divisor) : n; + forcedinline int safeModulo (int n, const int divisor) throw() + { + jassert (divisor > 0); + n %= divisor; + return (n < 0) ? (n + divisor) : n; + } } //============================================================================== diff --git a/src/gui/graphics/drawables/juce_DrawablePath.cpp b/src/gui/graphics/drawables/juce_DrawablePath.cpp index 7cda83b7a0..5340bd2bd0 100644 --- a/src/gui/graphics/drawables/juce_DrawablePath.cpp +++ b/src/gui/graphics/drawables/juce_DrawablePath.cpp @@ -279,28 +279,32 @@ void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* u } } -static const Point findCubicSubdivisionPoint (float proportion, const Point points[4]) +namespace DrawablePathHelpers { - const Point mid1 (points[0] + (points[1] - points[0]) * proportion), - mid2 (points[1] + (points[2] - points[1]) * proportion), - mid3 (points[2] + (points[3] - points[2]) * proportion); + const Point findCubicSubdivisionPoint (float proportion, const Point points[4]) + { + const Point mid1 (points[0] + (points[1] - points[0]) * proportion), + mid2 (points[1] + (points[2] - points[1]) * proportion), + mid3 (points[2] + (points[3] - points[2]) * proportion); - const Point newCp1 (mid1 + (mid2 - mid1) * proportion), - newCp2 (mid2 + (mid3 - mid2) * proportion); + const Point newCp1 (mid1 + (mid2 - mid1) * proportion), + newCp2 (mid2 + (mid3 - mid2) * proportion); - return newCp1 + (newCp2 - newCp1) * proportion; -} + return newCp1 + (newCp2 - newCp1) * proportion; + } -static const Point findQuadraticSubdivisionPoint (float proportion, const Point points[3]) -{ - const Point mid1 (points[0] + (points[1] - points[0]) * proportion), - mid2 (points[1] + (points[2] - points[1]) * proportion); + const Point findQuadraticSubdivisionPoint (float proportion, const Point points[3]) + { + const Point mid1 (points[0] + (points[1] - points[0]) * proportion), + mid2 (points[1] + (points[2] - points[1]) * proportion); - return mid1 + (mid2 - mid1) * proportion; + return mid1 + (mid2 - mid1) * proportion; + } } float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point& targetPoint, Expression::EvaluationContext* nameFinder) const { + using namespace DrawablePathHelpers; const Identifier i (state.getType()); float bestProp = 0; diff --git a/src/gui/graphics/drawables/juce_DrawableShape.cpp b/src/gui/graphics/drawables/juce_DrawableShape.cpp index a770ae3c78..e1a7e9d7a8 100644 --- a/src/gui/graphics/drawables/juce_DrawableShape.cpp +++ b/src/gui/graphics/drawables/juce_DrawableShape.cpp @@ -350,13 +350,16 @@ const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& return FillType(); } -static const Point calcThirdGradientPoint (const FillType& fillType) +namespace DrawableShapeHelpers { - const ColourGradient& g = *fillType.gradient; - const Point point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(), - g.point1.getY() + g.point1.getX() - g.point2.getX()); + const Point calcThirdGradientPoint (const FillType& fillType) + { + const ColourGradient& g = *fillType.gradient; + const Point point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(), + g.point1.getY() + g.point1.getX() - g.point2.getX()); - return point3Source.transformedBy (fillType.transform); + return point3Source.transformedBy (fillType.transform); + } } void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType, @@ -373,7 +376,7 @@ void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillT v.setProperty (type, "gradient", undoManager); v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager); v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager); - v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager); + v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager); v.setProperty (radial, fillType.gradient->isRadial, undoManager); diff --git a/src/gui/graphics/fonts/juce_Typeface.cpp b/src/gui/graphics/fonts/juce_Typeface.cpp index 503d99682f..0fa9345157 100644 --- a/src/gui/graphics/fonts/juce_Typeface.cpp +++ b/src/gui/graphics/fonts/juce_Typeface.cpp @@ -108,8 +108,8 @@ CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream) { clear(); - GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false); - BufferedInputStream in (&gzin, 32768, false); + GZIPDecompressorInputStream gzin (serialisedTypefaceStream); + BufferedInputStream in (gzin, 32768); name = in.readString(); isBold = in.readBool(); diff --git a/src/io/files/juce_ZipFile.cpp b/src/io/files/juce_ZipFile.cpp index 51613ced2e..87d397ea0b 100644 --- a/src/io/files/juce_ZipFile.cpp +++ b/src/io/files/juce_ZipFile.cpp @@ -280,7 +280,7 @@ void ZipFile::init() if (in != 0) { int numEntries = 0; - int pos = findEndOfZipEntryTable (in, numEntries); + int pos = findEndOfZipEntryTable (*in, numEntries); if (pos >= 0 && pos < in->getTotalLength()) { @@ -336,9 +336,9 @@ void ZipFile::init() } } -int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries) +int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries) { - BufferedInputStream in (input, 8192, false); + BufferedInputStream in (input, 8192); in.setPosition (in.getTotalLength()); int64 pos = in.getPosition(); diff --git a/src/io/files/juce_ZipFile.h b/src/io/files/juce_ZipFile.h index 52f1a83697..94a3c54ba8 100644 --- a/src/io/files/juce_ZipFile.h +++ b/src/io/files/juce_ZipFile.h @@ -187,7 +187,7 @@ private: #endif void init(); - int findEndOfZipEntryTable (InputStream* in, int& numEntries); + int findEndOfZipEntryTable (InputStream& input, int& numEntries); static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second); ZipFile (const ZipFile&); diff --git a/src/io/network/juce_Socket.cpp b/src/io/network/juce_Socket.cpp index d7e5ce8e87..9ea0df1e99 100644 --- a/src/io/network/juce_Socket.cpp +++ b/src/io/network/juce_Socket.cpp @@ -72,20 +72,20 @@ namespace SocketHelpers { typedef int (__stdcall juce_CloseWin32SocketLibCall) (void); static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0; -} -static void initWin32Sockets() -{ - static CriticalSection lock; - const ScopedLock sl (lock); - - if (SocketHelpers::juce_CloseWin32SocketLib == 0) + void initWin32Sockets() { - WSADATA wsaData; - const WORD wVersionRequested = MAKEWORD (1, 1); - WSAStartup (wVersionRequested, &wsaData); + static CriticalSection lock; + const ScopedLock sl (lock); - SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup; + if (SocketHelpers::juce_CloseWin32SocketLib == 0) + { + WSADATA wsaData; + const WORD wVersionRequested = MAKEWORD (1, 1); + WSAStartup (wVersionRequested, &wsaData); + + SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup; + } } } @@ -320,7 +320,7 @@ StreamingSocket::StreamingSocket() isListener (false) { #if JUCE_WINDOWS - initWin32Sockets(); + SocketHelpers::initWin32Sockets(); #endif } @@ -334,7 +334,7 @@ StreamingSocket::StreamingSocket (const String& hostName_, isListener (false) { #if JUCE_WINDOWS - initWin32Sockets(); + SocketHelpers::initWin32Sockets(); #endif SocketHelpers::resetSocketOptions (handle_, false, false); @@ -518,7 +518,7 @@ DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroad serverAddress (0) { #if JUCE_WINDOWS - initWin32Sockets(); + SocketHelpers::initWin32Sockets(); #endif handle = (int) socket (AF_INET, SOCK_DGRAM, 0); @@ -535,7 +535,7 @@ DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_, serverAddress (0) { #if JUCE_WINDOWS - initWin32Sockets(); + SocketHelpers::initWin32Sockets(); #endif SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast); diff --git a/src/io/network/juce_URL.cpp b/src/io/network/juce_URL.cpp index a773aa8ab3..0285d8dc3f 100644 --- a/src/io/network/juce_URL.cpp +++ b/src/io/network/juce_URL.cpp @@ -97,27 +97,41 @@ URL::~URL() { } -static const String getMangledParameters (const StringPairArray& parameters) +namespace URLHelpers { - String p; - - for (int i = 0; i < parameters.size(); ++i) + const String getMangledParameters (const StringPairArray& parameters) { - if (i > 0) - p << '&'; + String p; - p << URL::addEscapeChars (parameters.getAllKeys() [i], true) - << '=' - << URL::addEscapeChars (parameters.getAllValues() [i], true); + for (int i = 0; i < parameters.size(); ++i) + { + if (i > 0) + p << '&'; + + p << URL::addEscapeChars (parameters.getAllKeys() [i], true) + << '=' + << URL::addEscapeChars (parameters.getAllValues() [i], true); + } + + return p; } - return p; + int findStartOfDomain (const String& url) + { + int i = 0; + + while (CharacterFunctions::isLetterOrDigit (url[i]) + || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0) + ++i; + + return url[i] == ':' ? i + 1 : 0; + } } const String URL::toString (const bool includeGetParameters) const { if (includeGetParameters && parameters.size() > 0) - return url + "?" + getMangledParameters (parameters); + return url + "?" + URLHelpers::getMangledParameters (parameters); else return url; } @@ -128,20 +142,9 @@ bool URL::isWellFormed() const return url.isNotEmpty(); } -static int findStartOfDomain (const String& url) -{ - int i = 0; - - while (CharacterFunctions::isLetterOrDigit (url[i]) - || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0) - ++i; - - return url[i] == ':' ? i + 1 : 0; -} - const String URL::getDomain() const { - int start = findStartOfDomain (url); + int start = URLHelpers::findStartOfDomain (url); while (url[start] == '/') ++start; @@ -156,7 +159,7 @@ const String URL::getDomain() const const String URL::getSubPath() const { - int start = findStartOfDomain (url); + int start = URLHelpers::findStartOfDomain (url); while (url[start] == '/') ++start; @@ -168,12 +171,12 @@ const String URL::getSubPath() const const String URL::getScheme() const { - return url.substring (0, findStartOfDomain (url) - 1); + return url.substring (0, URLHelpers::findStartOfDomain (url) - 1); } const URL URL::withNewSubPath (const String& newPath) const { - int start = findStartOfDomain (url); + int start = URLHelpers::findStartOfDomain (url); while (url[start] == '/') ++start; @@ -406,7 +409,7 @@ private: } else { - data << getMangledParameters (url.getParameters()) + data << URLHelpers::getMangledParameters (url.getParameters()) << url.getPostData(); data.flush(); diff --git a/src/io/streams/juce_BufferedInputStream.cpp b/src/io/streams/juce_BufferedInputStream.cpp index 83c340fbb3..81cc98b764 100644 --- a/src/io/streams/juce_BufferedInputStream.cpp +++ b/src/io/streams/juce_BufferedInputStream.cpp @@ -29,23 +29,45 @@ BEGIN_JUCE_NAMESPACE #include "juce_BufferedInputStream.h" +namespace +{ + int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw() + { + // You need to supply a real stream when creating a BufferedInputStream + jassert (source != 0); + + requestedSize = jmax (256, requestedSize); + + const int64 sourceSize = source->getTotalLength(); + if (sourceSize >= 0 && sourceSize < requestedSize) + requestedSize = jmax (32, (int) sourceSize); + + return requestedSize; + } +} //============================================================================== -BufferedInputStream::BufferedInputStream (InputStream* const source_, - const int bufferSize_, +BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_, const bool deleteSourceWhenDestroyed) - : source (source_), - sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0), - bufferSize (jmax (256, bufferSize_)), - position (source_->getPosition()), + : source (sourceStream), + sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0), + bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)), + position (sourceStream->getPosition()), lastReadPos (0), + bufferStart (position), bufferOverlap (128) { - const int sourceSize = (int) source_->getTotalLength(); - if (sourceSize >= 0) - bufferSize = jmin (jmax (32, sourceSize), bufferSize); + buffer.malloc (bufferSize); +} - bufferStart = position; +BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_) + : source (&sourceStream), + bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)), + position (sourceStream.getPosition()), + lastReadPos (0), + bufferStart (position), + bufferOverlap (128) +{ buffer.malloc (bufferSize); } diff --git a/src/io/streams/juce_BufferedInputStream.h b/src/io/streams/juce_BufferedInputStream.h index 462fd717e9..03ad3bf5c6 100644 --- a/src/io/streams/juce_BufferedInputStream.h +++ b/src/io/streams/juce_BufferedInputStream.h @@ -53,6 +53,14 @@ public: int bufferSize, bool deleteSourceWhenDestroyed); + /** Creates a BufferedInputStream from an input source. + + @param sourceStream the source stream to read from - the source stream must not + be deleted until this object has been destroyed. + @param bufferSize the size of reservoir to use to buffer the source + */ + BufferedInputStream (InputStream& sourceStream, int bufferSize); + /** Destructor. This may also delete the source stream, if that option was chosen when the diff --git a/src/io/streams/juce_GZIPCompressorOutputStream.cpp b/src/io/streams/juce_GZIPCompressorOutputStream.cpp index 71bb7cb764..2ecb8f5260 100644 --- a/src/io/streams/juce_GZIPCompressorOutputStream.cpp +++ b/src/io/streams/juce_GZIPCompressorOutputStream.cpp @@ -45,7 +45,7 @@ BEGIN_JUCE_NAMESPACE //============================================================================== // internal helper object that holds the zlib structures so they don't have to be // included publicly. -class GZIPCompressorHelper +class GZIPCompressorOutputStream::GZIPCompressorHelper { public: GZIPCompressorHelper (const int compressionLevel, const bool nowrap) @@ -118,6 +118,8 @@ public: return 0; } + enum { gzipCompBufferSize = 32768 }; + private: zlibNamespace::z_stream stream; const uint8* data; @@ -130,15 +132,13 @@ public: //============================================================================== -const int gzipCompBufferSize = 32768; - GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_, int compressionLevel, const bool deleteDestStream, const bool noWrap) : destStream (destStream_), streamToDelete (deleteDestStream ? destStream_ : 0), - buffer (gzipCompBufferSize) + buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize) { if (compressionLevel < 1 || compressionLevel > 9) compressionLevel = -1; @@ -183,7 +183,7 @@ bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany) bool GZIPCompressorOutputStream::doNextBlock() { - const int len = helper->doNextBlock (buffer, gzipCompBufferSize); + const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize); if (len > 0) return destStream->write (buffer, len); diff --git a/src/io/streams/juce_GZIPCompressorOutputStream.h b/src/io/streams/juce_GZIPCompressorOutputStream.h index 5ae4bc59d7..efeeb5a2d6 100644 --- a/src/io/streams/juce_GZIPCompressorOutputStream.h +++ b/src/io/streams/juce_GZIPCompressorOutputStream.h @@ -28,7 +28,6 @@ #include "juce_OutputStream.h" #include "../../containers/juce_ScopedPointer.h" -class GZIPCompressorHelper; //============================================================================== @@ -76,6 +75,8 @@ private: OutputStream* const destStream; ScopedPointer streamToDelete; HeapBlock buffer; + class GZIPCompressorHelper; + friend class ScopedPointer ; ScopedPointer helper; bool doNextBlock(); diff --git a/src/io/streams/juce_GZIPDecompressorInputStream.cpp b/src/io/streams/juce_GZIPDecompressorInputStream.cpp index e6a4ea3b8a..2bd389e42d 100644 --- a/src/io/streams/juce_GZIPDecompressorInputStream.cpp +++ b/src/io/streams/juce_GZIPDecompressorInputStream.cpp @@ -74,7 +74,7 @@ BEGIN_JUCE_NAMESPACE //============================================================================== // internal helper object that holds the zlib structures so they don't have to be // included publicly. -class GZIPDecompressHelper +class GZIPDecompressorInputStream::GZIPDecompressHelper { public: GZIPDecompressHelper (const bool noWrap) @@ -146,6 +146,8 @@ public: bool finished, needsDictionary, error, streamIsValid; + enum { gzipDecompBufferSize = 32768 }; + private: zlibNamespace::z_stream stream; uint8* data; @@ -156,8 +158,6 @@ private: }; //============================================================================== -const int gzipDecompBufferSize = 32768; - GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_, const bool deleteSourceWhenDestroyed, const bool noWrap_, @@ -170,11 +170,24 @@ GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sou activeBufferSize (0), originalSourcePos (sourceStream_->getPosition()), currentPos (0), - buffer (gzipDecompBufferSize), + buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize), helper (new GZIPDecompressHelper (noWrap_)) { } +GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_) + : sourceStream (&sourceStream_), + uncompressedStreamLength (-1), + noWrap (false), + isEof (false), + activeBufferSize (0), + originalSourcePos (sourceStream_.getPosition()), + currentPos (0), + buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize), + helper (new GZIPDecompressHelper (false)) +{ +} + GZIPDecompressorInputStream::~GZIPDecompressorInputStream() { } @@ -210,7 +223,7 @@ int GZIPDecompressorInputStream::read (void* destBuffer, int howMany) if (helper->needsInput()) { - activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize); + activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize); if (activeBufferSize > 0) { diff --git a/src/io/streams/juce_GZIPDecompressorInputStream.h b/src/io/streams/juce_GZIPDecompressorInputStream.h index c7cdffc8fa..6f6d96d18e 100644 --- a/src/io/streams/juce_GZIPDecompressorInputStream.h +++ b/src/io/streams/juce_GZIPDecompressorInputStream.h @@ -28,7 +28,6 @@ #include "juce_InputStream.h" #include "../../containers/juce_ScopedPointer.h" -class GZIPDecompressHelper; //============================================================================== @@ -61,6 +60,13 @@ public: bool noWrap = false, int64 uncompressedStreamLength = -1); + /** Creates a decompressor stream. + + @param sourceStream the stream to read from - the source stream must not be + deleted until this object has been destroyed + */ + GZIPDecompressorInputStream (InputStream& sourceStream); + /** Destructor. */ ~GZIPDecompressorInputStream(); @@ -84,6 +90,9 @@ private: int activeBufferSize; int64 originalSourcePos, currentPos; HeapBlock buffer; + + class GZIPDecompressHelper; + friend class ScopedPointer ; ScopedPointer helper; GZIPDecompressorInputStream (const GZIPDecompressorInputStream&); diff --git a/src/native/common/juce_posix_SharedCode.h b/src/native/common/juce_posix_SharedCode.h index 6ee0e83860..9dce34034e 100644 --- a/src/native/common/juce_posix_SharedCode.h +++ b/src/native/common/juce_posix_SharedCode.h @@ -220,20 +220,37 @@ bool File::setAsCurrentWorkingDirectory() const } //============================================================================== -#if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T - typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug) -#else - typedef struct stat juce_statStruct; -#endif - -static bool juce_stat (const String& fileName, juce_statStruct& info) +namespace { - return fileName.isNotEmpty() - #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T - && (stat64 (fileName.toUTF8(), &info) == 0); - #else - && (stat (fileName.toUTF8(), &info) == 0); - #endif + #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T + typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug) + #else + typedef struct stat juce_statStruct; + #endif + + bool juce_stat (const String& fileName, juce_statStruct& info) + { + return fileName.isNotEmpty() + #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T + && (stat64 (fileName.toUTF8(), &info) == 0); + #else + && (stat (fileName.toUTF8(), &info) == 0); + #endif + } + + // if this file doesn't exist, find a parent of it that does.. + bool juce_doStatFS (File f, struct statfs& result) + { + for (int i = 5; --i >= 0;) + { + if (f.exists()) + break; + + f = f.getParentDirectory(); + } + + return statfs (f.getFullPathName().toUTF8(), &result) == 0; + } } bool File::isDirectory() const @@ -445,20 +462,6 @@ const File juce_getExecutableFile() } //============================================================================== -// if this file doesn't exist, find a parent of it that does.. -static bool juce_doStatFS (File f, struct statfs& result) -{ - for (int i = 5; --i >= 0;) - { - if (f.exists()) - break; - - f = f.getParentDirectory(); - } - - return statfs (f.getFullPathName().toUTF8(), &result) == 0; -} - int64 File::getBytesFreeOnVolume() const { struct statfs buf; diff --git a/src/native/juce_mac_NativeCode.mm b/src/native/juce_mac_NativeCode.mm index 633b48f0a8..9d0efded75 100644 --- a/src/native/juce_mac_NativeCode.mm +++ b/src/native/juce_mac_NativeCode.mm @@ -88,22 +88,25 @@ BEGIN_JUCE_NAMESPACE #include "common/juce_MidiDataConcatenator.h" #undef Point -template -static const Rectangle convertToRectInt (const RectType& r) +namespace { - return Rectangle ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height); -} + template + const Rectangle convertToRectInt (const RectType& r) + { + return Rectangle ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height); + } -template -static const Rectangle convertToRectFloat (const RectType& r) -{ - return Rectangle (r.origin.x, r.origin.y, r.size.width, r.size.height); -} + template + const Rectangle convertToRectFloat (const RectType& r) + { + return Rectangle (r.origin.x, r.origin.y, r.size.width, r.size.height); + } -template -static CGRect convertToCGRect (const RectType& r) -{ - return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight()); + template + CGRect convertToCGRect (const RectType& r) + { + return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight()); + } } //============================================================================== diff --git a/src/native/linux/juce_linux_Audio.cpp b/src/native/linux/juce_linux_Audio.cpp index 535d219aa1..871925bff2 100644 --- a/src/native/linux/juce_linux_Audio.cpp +++ b/src/native/linux/juce_linux_Audio.cpp @@ -29,85 +29,88 @@ //============================================================================== -static void getDeviceSampleRates (snd_pcm_t* handle, Array & rates) +namespace { - const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 }; - - snd_pcm_hw_params_t* hwParams; - snd_pcm_hw_params_alloca (&hwParams); - - for (int i = 0; ratesToTry[i] != 0; ++i) + void getDeviceSampleRates (snd_pcm_t* handle, Array & rates) { - if (snd_pcm_hw_params_any (handle, hwParams) >= 0 - && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0) + const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 }; + + snd_pcm_hw_params_t* hwParams; + snd_pcm_hw_params_alloca (&hwParams); + + for (int i = 0; ratesToTry[i] != 0; ++i) { - rates.addIfNotAlreadyThere (ratesToTry[i]); - } - } -} - -static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans) -{ - snd_pcm_hw_params_t *params; - snd_pcm_hw_params_alloca (¶ms); - - if (snd_pcm_hw_params_any (handle, params) >= 0) - { - snd_pcm_hw_params_get_channels_min (params, minChans); - snd_pcm_hw_params_get_channels_max (params, maxChans); - } -} - -static void getDeviceProperties (const String& deviceID, - unsigned int& minChansOut, - unsigned int& maxChansOut, - unsigned int& minChansIn, - unsigned int& maxChansIn, - Array & rates) -{ - if (deviceID.isEmpty()) - return; - - snd_ctl_t* handle; - - if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0) - { - snd_pcm_info_t* info; - snd_pcm_info_alloca (&info); - - snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK); - snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue()); - snd_pcm_info_set_subdevice (info, 0); - - if (snd_ctl_pcm_info (handle, info) >= 0) - { - snd_pcm_t* pcmHandle; - if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0) + if (snd_pcm_hw_params_any (handle, hwParams) >= 0 + && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0) { - getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut); - getDeviceSampleRates (pcmHandle, rates); - - snd_pcm_close (pcmHandle); + rates.addIfNotAlreadyThere (ratesToTry[i]); } } + } - snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE); + void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans) + { + snd_pcm_hw_params_t *params; + snd_pcm_hw_params_alloca (¶ms); - if (snd_ctl_pcm_info (handle, info) >= 0) + if (snd_pcm_hw_params_any (handle, params) >= 0) { - snd_pcm_t* pcmHandle; - if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0) - { - getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn); + snd_pcm_hw_params_get_channels_min (params, minChans); + snd_pcm_hw_params_get_channels_max (params, maxChans); + } + } - if (rates.size() == 0) + void getDeviceProperties (const String& deviceID, + unsigned int& minChansOut, + unsigned int& maxChansOut, + unsigned int& minChansIn, + unsigned int& maxChansIn, + Array & rates) + { + if (deviceID.isEmpty()) + return; + + snd_ctl_t* handle; + + if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0) + { + snd_pcm_info_t* info; + snd_pcm_info_alloca (&info); + + snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK); + snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue()); + snd_pcm_info_set_subdevice (info, 0); + + if (snd_ctl_pcm_info (handle, info) >= 0) + { + snd_pcm_t* pcmHandle; + if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0) + { + getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut); getDeviceSampleRates (pcmHandle, rates); - snd_pcm_close (pcmHandle); + snd_pcm_close (pcmHandle); + } } - } - snd_ctl_close (handle); + snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE); + + if (snd_ctl_pcm_info (handle, info) >= 0) + { + snd_pcm_t* pcmHandle; + if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0) + { + getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn); + + if (rates.size() == 0) + getDeviceSampleRates (pcmHandle, rates); + + snd_pcm_close (pcmHandle); + } + } + + snd_ctl_close (handle); + } } } diff --git a/src/native/linux/juce_linux_Files.cpp b/src/native/linux/juce_linux_Files.cpp index 0d9a3ff757..ff2cd1e86f 100644 --- a/src/native/linux/juce_linux_Files.cpp +++ b/src/native/linux/juce_linux_Files.cpp @@ -27,10 +27,13 @@ // compiled on its own). #if JUCE_INCLUDED_FILE -static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h -static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h -static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h -static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h +enum +{ + U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h + U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h + U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h + U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h +}; //============================================================================== bool File::copyInternal (const File& dest) const @@ -66,7 +69,7 @@ bool File::isOnCDRomDrive() const struct statfs buf; return statfs (getFullPathName().toUTF8(), &buf) == 0 - && buf.f_type == U_ISOFS_SUPER_MAGIC; + && buf.f_type == (short) U_ISOFS_SUPER_MAGIC; } bool File::isOnHardDisk() const @@ -107,18 +110,21 @@ bool File::isHidden() const } //============================================================================== -static const File juce_readlink (const String& file, const File& defaultFile) +namespace { - const int size = 8192; - HeapBlock buffer; - buffer.malloc (size + 4); + const File juce_readlink (const String& file, const File& defaultFile) + { + const int size = 8192; + HeapBlock buffer; + buffer.malloc (size + 4); - const size_t numBytes = readlink (file.toUTF8(), buffer, size); + const size_t numBytes = readlink (file.toUTF8(), buffer, size); - if (numBytes > 0 && numBytes <= size) - return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes)); + if (numBytes > 0 && numBytes <= size) + return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes)); - return defaultFile; + return defaultFile; + } } const File File::getLinkedTarget() const diff --git a/src/native/linux/juce_linux_Fonts.cpp b/src/native/linux/juce_linux_Fonts.cpp index ee8342d818..011211538f 100644 --- a/src/native/linux/juce_linux_Fonts.cpp +++ b/src/native/linux/juce_linux_Fonts.cpp @@ -510,54 +510,57 @@ const StringArray Font::findAllTypefaceNames() return s; } -static const String pickBestFont (const StringArray& names, - const char* const choicesString) +namespace { - StringArray choices; - choices.addTokens (String (choicesString), ",", String::empty); - choices.trim(); - choices.removeEmptyStrings(); + const String pickBestFont (const StringArray& names, + const char* const choicesString) + { + StringArray choices; + choices.addTokens (String (choicesString), ",", String::empty); + choices.trim(); + choices.removeEmptyStrings(); - int i, j; - for (j = 0; j < choices.size(); ++j) - if (names.contains (choices[j], true)) - return choices[j]; + int i, j; + for (j = 0; j < choices.size(); ++j) + if (names.contains (choices[j], true)) + return choices[j]; - for (j = 0; j < choices.size(); ++j) - for (i = 0; i < names.size(); i++) - if (names[i].startsWithIgnoreCase (choices[j])) - return names[i]; + for (j = 0; j < choices.size(); ++j) + for (i = 0; i < names.size(); i++) + if (names[i].startsWithIgnoreCase (choices[j])) + return names[i]; - for (j = 0; j < choices.size(); ++j) - for (i = 0; i < names.size(); i++) - if (names[i].containsIgnoreCase (choices[j])) - return names[i]; + for (j = 0; j < choices.size(); ++j) + for (i = 0; i < names.size(); i++) + if (names[i].containsIgnoreCase (choices[j])) + return names[i]; - return names[0]; -} + return names[0]; + } -static const String linux_getDefaultSansSerifFontName() -{ - StringArray allFonts; - FreeTypeInterface::getInstance()->getSansSerifNames (allFonts); + const String linux_getDefaultSansSerifFontName() + { + StringArray allFonts; + FreeTypeInterface::getInstance()->getSansSerifNames (allFonts); - return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans"); -} + return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans"); + } -static const String linux_getDefaultSerifFontName() -{ - StringArray allFonts; - FreeTypeInterface::getInstance()->getSerifNames (allFonts); + const String linux_getDefaultSerifFontName() + { + StringArray allFonts; + FreeTypeInterface::getInstance()->getSerifNames (allFonts); - return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif"); -} + return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif"); + } -static const String linux_getDefaultMonospacedFontName() -{ - StringArray allFonts; - FreeTypeInterface::getInstance()->getMonospacedNames (allFonts); + const String linux_getDefaultMonospacedFontName() + { + StringArray allFonts; + FreeTypeInterface::getInstance()->getMonospacedNames (allFonts); - return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono"); + return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono"); + } } void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) diff --git a/src/native/linux/juce_linux_JackAudio.cpp b/src/native/linux/juce_linux_JackAudio.cpp index 92da40660d..9281a1f7bb 100644 --- a/src/native/linux/juce_linux_JackAudio.cpp +++ b/src/native/linux/juce_linux_JackAudio.cpp @@ -84,19 +84,22 @@ JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, #endif #if JACK_LOGGING_ENABLED -static void jack_Log (const String& s) +namespace { - std::cerr << s << std::endl; -} + void jack_Log (const String& s) + { + std::cerr << s << std::endl; + } -static void dumpJackErrorMessage (const jack_status_t status) -{ - if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server"); - if (status & JackVersionError) jack_Log ("Client's protocol version does not match"); - if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option"); - if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique"); - if (status & JackNoSuchClient) jack_Log ("Requested client does not exist"); - if (status & JackInitFailure) jack_Log ("Unable to initialize client"); + void dumpJackErrorMessage (const jack_status_t status) + { + if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server"); + if (status & JackVersionError) jack_Log ("Client's protocol version does not match"); + if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option"); + if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique"); + if (status & JackNoSuchClient) jack_Log ("Requested client does not exist"); + if (status & JackInitFailure) jack_Log ("Unable to initialize client"); + } } #else #define dumpJackErrorMessage(a) {} diff --git a/src/native/linux/juce_linux_Midi.cpp b/src/native/linux/juce_linux_Midi.cpp index 337654be8d..1f911326f4 100644 --- a/src/native/linux/juce_linux_Midi.cpp +++ b/src/native/linux/juce_linux_Midi.cpp @@ -29,125 +29,128 @@ #if JUCE_ALSA //============================================================================== -static snd_seq_t* iterateMidiDevices (const bool forInput, - StringArray& deviceNamesFound, - const int deviceIndexToOpen) +namespace { - snd_seq_t* returnedHandle = 0; - snd_seq_t* seqHandle; - - if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT - : SND_SEQ_OPEN_OUTPUT, 0) == 0) + snd_seq_t* iterateMidiDevices (const bool forInput, + StringArray& deviceNamesFound, + const int deviceIndexToOpen) { - snd_seq_system_info_t* systemInfo; - snd_seq_client_info_t* clientInfo; + snd_seq_t* returnedHandle = 0; + snd_seq_t* seqHandle; - if (snd_seq_system_info_malloc (&systemInfo) == 0) + if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT + : SND_SEQ_OPEN_OUTPUT, 0) == 0) { - if (snd_seq_system_info (seqHandle, systemInfo) == 0 - && snd_seq_client_info_malloc (&clientInfo) == 0) + snd_seq_system_info_t* systemInfo; + snd_seq_client_info_t* clientInfo; + + if (snd_seq_system_info_malloc (&systemInfo) == 0) { - int numClients = snd_seq_system_info_get_cur_clients (systemInfo); - - while (--numClients >= 0 && returnedHandle == 0) + if (snd_seq_system_info (seqHandle, systemInfo) == 0 + && snd_seq_client_info_malloc (&clientInfo) == 0) { - if (snd_seq_query_next_client (seqHandle, clientInfo) == 0) + int numClients = snd_seq_system_info_get_cur_clients (systemInfo); + + while (--numClients >= 0 && returnedHandle == 0) { - snd_seq_port_info_t* portInfo; - if (snd_seq_port_info_malloc (&portInfo) == 0) + if (snd_seq_query_next_client (seqHandle, clientInfo) == 0) { - int numPorts = snd_seq_client_info_get_num_ports (clientInfo); - const int client = snd_seq_client_info_get_client (clientInfo); - - snd_seq_port_info_set_client (portInfo, client); - snd_seq_port_info_set_port (portInfo, -1); - - while (--numPorts >= 0) + snd_seq_port_info_t* portInfo; + if (snd_seq_port_info_malloc (&portInfo) == 0) { - if (snd_seq_query_next_port (seqHandle, portInfo) == 0 - && (snd_seq_port_info_get_capability (portInfo) - & (forInput ? SND_SEQ_PORT_CAP_READ - : SND_SEQ_PORT_CAP_WRITE)) != 0) + int numPorts = snd_seq_client_info_get_num_ports (clientInfo); + const int client = snd_seq_client_info_get_client (clientInfo); + + snd_seq_port_info_set_client (portInfo, client); + snd_seq_port_info_set_port (portInfo, -1); + + while (--numPorts >= 0) { - deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo)); - - if (deviceNamesFound.size() == deviceIndexToOpen + 1) + if (snd_seq_query_next_port (seqHandle, portInfo) == 0 + && (snd_seq_port_info_get_capability (portInfo) + & (forInput ? SND_SEQ_PORT_CAP_READ + : SND_SEQ_PORT_CAP_WRITE)) != 0) { - const int sourcePort = snd_seq_port_info_get_port (portInfo); - const int sourceClient = snd_seq_client_info_get_client (clientInfo); + deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo)); - if (sourcePort != -1) + if (deviceNamesFound.size() == deviceIndexToOpen + 1) { - snd_seq_set_client_name (seqHandle, - forInput ? "Juce Midi Input" - : "Juce Midi Output"); + const int sourcePort = snd_seq_port_info_get_port (portInfo); + const int sourceClient = snd_seq_client_info_get_client (clientInfo); - const int portId - = snd_seq_create_simple_port (seqHandle, - forInput ? "Juce Midi In Port" - : "Juce Midi Out Port", - forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE) - : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), - SND_SEQ_PORT_TYPE_MIDI_GENERIC); + if (sourcePort != -1) + { + snd_seq_set_client_name (seqHandle, + forInput ? "Juce Midi Input" + : "Juce Midi Output"); - snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort); + const int portId + = snd_seq_create_simple_port (seqHandle, + forInput ? "Juce Midi In Port" + : "Juce Midi Out Port", + forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE) + : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), + SND_SEQ_PORT_TYPE_MIDI_GENERIC); - returnedHandle = seqHandle; + snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort); + + returnedHandle = seqHandle; + } } } } - } - snd_seq_port_info_free (portInfo); + snd_seq_port_info_free (portInfo); + } } } + + snd_seq_client_info_free (clientInfo); } - snd_seq_client_info_free (clientInfo); + snd_seq_system_info_free (systemInfo); } - snd_seq_system_info_free (systemInfo); + if (returnedHandle == 0) + snd_seq_close (seqHandle); } - if (returnedHandle == 0) - snd_seq_close (seqHandle); + deviceNamesFound.appendNumbersToDuplicates (true, true); + + return returnedHandle; } - deviceNamesFound.appendNumbersToDuplicates (true, true); - - return returnedHandle; -} - -static snd_seq_t* createMidiDevice (const bool forInput, - const String& deviceNameToOpen) -{ - snd_seq_t* seqHandle = 0; - - if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT - : SND_SEQ_OPEN_OUTPUT, 0) == 0) + snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen) { - snd_seq_set_client_name (seqHandle, - (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString()); + snd_seq_t* seqHandle = 0; - const int portId - = snd_seq_create_simple_port (seqHandle, - forInput ? "in" - : "out", - forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE) - : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), - forInput ? SND_SEQ_PORT_TYPE_APPLICATION - : SND_SEQ_PORT_TYPE_MIDI_GENERIC); - - if (portId < 0) + if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT + : SND_SEQ_OPEN_OUTPUT, 0) == 0) { - snd_seq_close (seqHandle); - seqHandle = 0; - } - } + snd_seq_set_client_name (seqHandle, + (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString()); - return seqHandle; + const int portId + = snd_seq_create_simple_port (seqHandle, + forInput ? "in" + : "out", + forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE) + : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ), + forInput ? SND_SEQ_PORT_TYPE_APPLICATION + : SND_SEQ_PORT_TYPE_MIDI_GENERIC); + + if (portId < 0) + { + snd_seq_close (seqHandle); + seqHandle = 0; + } + } + + return seqHandle; + } } + //============================================================================== class MidiOutputDevice { diff --git a/src/native/linux/juce_linux_SystemStats.cpp b/src/native/linux/juce_linux_SystemStats.cpp index 37bb439908..f4d4e2cdc5 100644 --- a/src/native/linux/juce_linux_SystemStats.cpp +++ b/src/native/linux/juce_linux_SystemStats.cpp @@ -56,26 +56,50 @@ bool SystemStats::isOperatingSystem64Bit() } //============================================================================== -static const String juce_getCpuInfo (const char* const key) +namespace LinuxStatsHelpers { - StringArray lines; - lines.addLines (File ("/proc/cpuinfo").loadFileAsString()); + const String getCpuInfo (const char* const key) + { + StringArray lines; + lines.addLines (File ("/proc/cpuinfo").loadFileAsString()); - for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order) - if (lines[i].startsWithIgnoreCase (key)) - return lines[i].fromFirstOccurrenceOf (":", false, false).trim(); + for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order) + if (lines[i].startsWithIgnoreCase (key)) + return lines[i].fromFirstOccurrenceOf (":", false, false).trim(); - return String::empty; + return String::empty; + } + + bool getTimeSinceStartup (timeval* const t) throw() + { + if (gettimeofday (t, 0) != 0) + return false; + + static unsigned int calibrate = 0; + static bool calibrated = false; + + if (! calibrated) + { + calibrated = true; + + struct sysinfo sysi; + if (sysinfo (&sysi) == 0) + calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970! + } + + t->tv_sec -= calibrate; + return true; + } } const String SystemStats::getCpuVendor() { - return juce_getCpuInfo ("vendor_id"); + return LinuxStatsHelpers::getCpuInfo ("vendor_id"); } int SystemStats::getCpuSpeedInMegaherz() { - return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue()); + return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue()); } int SystemStats::getMemorySizeInMegabytes() @@ -116,13 +140,13 @@ const String SystemStats::getFullUserName() //============================================================================== void SystemStats::initialiseStats() { - const String flags (juce_getCpuInfo ("flags")); + const String flags (LinuxStatsHelpers::getCpuInfo ("flags")); cpuFlags.hasMMX = flags.contains ("mmx"); cpuFlags.hasSSE = flags.contains ("sse"); cpuFlags.hasSSE2 = flags.contains ("sse2"); cpuFlags.has3DNow = flags.contains ("3dnow"); - cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1; + cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1; } void PlatformUtilities::fpuReset() @@ -130,31 +154,10 @@ void PlatformUtilities::fpuReset() } //============================================================================== -static bool juce_getTimeSinceStartup (timeval* const t) throw() -{ - if (gettimeofday (t, 0) != 0) - return false; - - static unsigned int calibrate = 0; - static bool calibrated = false; - - if (! calibrated) - { - calibrated = true; - - struct sysinfo sysi; - if (sysinfo (&sysi) == 0) - calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970! - } - - t->tv_sec -= calibrate; - return true; -} - uint32 juce_millisecondsSinceStartup() throw() { timeval t; - if (juce_getTimeSinceStartup (&t)) + if (LinuxStatsHelpers::getTimeSinceStartup (&t)) return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000)); return 0; @@ -163,7 +166,7 @@ uint32 juce_millisecondsSinceStartup() throw() int64 Time::getHighResolutionTicks() throw() { timeval t; - if (juce_getTimeSinceStartup (&t)) + if (LinuxStatsHelpers::getTimeSinceStartup (&t)) return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec; return 0; diff --git a/src/native/mac/juce_iphone_MessageManager.mm b/src/native/mac/juce_iphone_MessageManager.mm index 7eecb7d28a..9424d99894 100644 --- a/src/native/mac/juce_iphone_MessageManager.mm +++ b/src/native/mac/juce_iphone_MessageManager.mm @@ -107,36 +107,40 @@ bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor) } //============================================================================== -static CFRunLoopRef runLoop = 0; -static CFRunLoopSourceRef runLoopSource = 0; -static OwnedArray * pendingMessages = 0; -static JuceCustomMessageHandler* juceCustomMessageHandler = 0; - -static void runLoopSourceCallback (void*) +namespace iOSMessageLoopHelpers { - if (pendingMessages != 0) + static CFRunLoopRef runLoop = 0; + static CFRunLoopSourceRef runLoopSource = 0; + static OwnedArray * pendingMessages = 0; + static JuceCustomMessageHandler* juceCustomMessageHandler = 0; + + void runLoopSourceCallback (void*) { - int numDispatched = 0; - - do + if (pendingMessages != 0) { - Message* const nextMessage = pendingMessages->removeAndReturn (0); + int numDispatched = 0; - if (nextMessage == 0) - return; + do + { + Message* const nextMessage = pendingMessages->removeAndReturn (0); - const ScopedAutoReleasePool pool; - MessageManager::getInstance()->deliverMessage (nextMessage); + if (nextMessage == 0) + return; - } while (++numDispatched <= 4); + const ScopedAutoReleasePool pool; + MessageManager::getInstance()->deliverMessage (nextMessage); - CFRunLoopSourceSignal (runLoopSource); - CFRunLoopWakeUp (runLoop); + } while (++numDispatched <= 4); + + CFRunLoopSourceSignal (runLoopSource); + CFRunLoopWakeUp (runLoop); + } } } void MessageManager::doPlatformSpecificInitialisation() { + using namespace iOSMessageLoopHelpers; pendingMessages = new OwnedArray (); runLoop = CFRunLoopGetCurrent(); @@ -152,6 +156,7 @@ void MessageManager::doPlatformSpecificInitialisation() void MessageManager::doPlatformSpecificShutdown() { + using namespace iOSMessageLoopHelpers; CFRunLoopSourceInvalidate (runLoopSource); CFRelease (runLoopSource); runLoopSource = 0; @@ -167,6 +172,8 @@ void MessageManager::doPlatformSpecificShutdown() bool juce_postMessageToSystemQueue (Message* message) { + using namespace iOSMessageLoopHelpers; + if (pendingMessages != 0) { pendingMessages->add (message); @@ -183,6 +190,8 @@ void MessageManager::broadcastMessage (const String& value) void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data) { + using namespace iOSMessageLoopHelpers; + if (isThisTheMessageThread()) { return (*callback) (data); diff --git a/src/native/mac/juce_iphone_UIViewComponentPeer.mm b/src/native/mac/juce_iphone_UIViewComponentPeer.mm index 0d7facd2d4..38a3bac6d8 100644 --- a/src/native/mac/juce_iphone_UIViewComponentPeer.mm +++ b/src/native/mac/juce_iphone_UIViewComponentPeer.mm @@ -614,18 +614,21 @@ bool UIViewComponentPeer::isFullScreen() const return fullScreen; } -static Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation) +namespace { - switch (interfaceOrientation) + Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation) { - case UIInterfaceOrientationPortrait: return Desktop::upright; - case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown; - case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise; - case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise; - default: jassertfalse; // unknown orientation! - } + switch (interfaceOrientation) + { + case UIInterfaceOrientationPortrait: return Desktop::upright; + case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown; + case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise; + case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise; + default: jassertfalse; // unknown orientation! + } - return Desktop::upright; + return Desktop::upright; + } } BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation) diff --git a/src/native/mac/juce_mac_AppleRemote.mm b/src/native/mac/juce_mac_AppleRemote.mm index 23e2967480..698bd2ab2b 100644 --- a/src/native/mac/juce_mac_AppleRemote.mm +++ b/src/native/mac/juce_mac_AppleRemote.mm @@ -40,50 +40,59 @@ AppleRemoteDevice::~AppleRemoteDevice() stop(); } -static io_object_t getAppleRemoteDevice() +namespace { - CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController"); - - io_iterator_t iter = 0; - io_object_t iod = 0; - - if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess - && iter != 0) + io_object_t getAppleRemoteDevice() { - iod = IOIteratorNext (iter); - } + CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController"); - IOObjectRelease (iter); - return iod; -} + io_iterator_t iter = 0; + io_object_t iod = 0; -static bool createAppleRemoteInterface (io_object_t iod, void** device) -{ - jassert (*device == 0); - io_name_t classname; - - if (IOObjectGetClass (iod, classname) == kIOReturnSuccess) - { - IOCFPlugInInterface** cfPlugInInterface = 0; - SInt32 score = 0; - - if (IOCreatePlugInInterfaceForService (iod, - kIOHIDDeviceUserClientTypeID, - kIOCFPlugInInterfaceID, - &cfPlugInInterface, - &score) == kIOReturnSuccess) + if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess + && iter != 0) { - HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface, - CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), - device); - - (void) hr; - - (*cfPlugInInterface)->Release (cfPlugInInterface); + iod = IOIteratorNext (iter); } + + IOObjectRelease (iter); + return iod; } - return *device != 0; + bool createAppleRemoteInterface (io_object_t iod, void** device) + { + jassert (*device == 0); + io_name_t classname; + + if (IOObjectGetClass (iod, classname) == kIOReturnSuccess) + { + IOCFPlugInInterface** cfPlugInInterface = 0; + SInt32 score = 0; + + if (IOCreatePlugInInterfaceForService (iod, + kIOHIDDeviceUserClientTypeID, + kIOCFPlugInInterfaceID, + &cfPlugInInterface, + &score) == kIOReturnSuccess) + { + HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface, + CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID), + device); + + (void) hr; + + (*cfPlugInInterface)->Release (cfPlugInInterface); + } + } + + return *device != 0; + } + + void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*) + { + if (result == kIOReturnSuccess) + ((AppleRemoteDevice*) target)->handleCallbackInternal(); + } } bool AppleRemoteDevice::start (const bool inExclusiveMode) @@ -132,12 +141,6 @@ bool AppleRemoteDevice::isActive() const return queue != 0; } -static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*) -{ - if (result == kIOReturnSuccess) - ((AppleRemoteDevice*) target)->handleCallbackInternal(); -} - bool AppleRemoteDevice::open (const bool openInExclusiveMode) { Array cookies; diff --git a/src/native/mac/juce_mac_AudioCDBurner.mm b/src/native/mac/juce_mac_AudioCDBurner.mm index 09cb9c6d5e..bf0be2b6ba 100644 --- a/src/native/mac/juce_mac_AudioCDBurner.mm +++ b/src/native/mac/juce_mac_AudioCDBurner.mm @@ -447,20 +447,23 @@ AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex) return b.release(); } -static NSArray* findDiskBurnerDevices() +namespace { - NSMutableArray* results = [NSMutableArray array]; - NSArray* devs = [DRDevice devices]; - - for (int i = 0; i < [devs count]; ++i) + NSArray* findDiskBurnerDevices() { - NSDictionary* dic = [[devs objectAtIndex: i] info]; - NSString* name = [dic valueForKey: DRDeviceProductNameKey]; - if (name != nil) - [results addObject: name]; - } + NSMutableArray* results = [NSMutableArray array]; + NSArray* devs = [DRDevice devices]; - return results; + for (int i = 0; i < [devs count]; ++i) + { + NSDictionary* dic = [[devs objectAtIndex: i] info]; + NSString* name = [dic valueForKey: DRDeviceProductNameKey]; + if (name != nil) + [results addObject: name]; + } + + return results; + } } const StringArray AudioCDBurner::findAvailableDevices() diff --git a/src/native/mac/juce_mac_Files.mm b/src/native/mac/juce_mac_Files.mm index 620ab167f5..b35d2b10c3 100644 --- a/src/native/mac/juce_mac_Files.mm +++ b/src/native/mac/juce_mac_Files.mm @@ -57,20 +57,55 @@ void File::findFileSystemRoots (Array& destArray) //============================================================================== -static bool isFileOnDriveType (const File& f, const char* const* types) +namespace { - struct statfs buf; - - if (juce_doStatFS (f, buf)) + bool isFileOnDriveType (const File& f, const char* const* types) { - const String type (buf.f_fstypename); + struct statfs buf; - while (*types != 0) - if (type.equalsIgnoreCase (*types++)) - return true; + if (juce_doStatFS (f, buf)) + { + const String type (buf.f_fstypename); + + while (*types != 0) + if (type.equalsIgnoreCase (*types++)) + return true; + } + + return false; } - return false; + bool juce_isHiddenFile (const String& path) + { + #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 + const ScopedAutoReleasePool pool; + NSNumber* hidden = nil; + NSError* err = nil; + + return [[NSURL fileURLWithPath: juceStringToNS (path)] + getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err] + && [hidden boolValue]; + #else + #if JUCE_IOS + return File (path).getFileName().startsWithChar ('.'); + #else + FSRef ref; + LSItemInfoRecord info; + + return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr + && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr + && (info.flags & kLSItemInfoIsInvisible) != 0; + #endif + #endif + } + +#if JUCE_IOS + const String getIOSSystemLocation (NSSearchPathDirectory type) + { + return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES) + objectAtIndex: 0]); + } +#endif } bool File::isOnCDRomDrive() const @@ -107,43 +142,11 @@ bool File::isOnRemovableDrive() const #endif } -static bool juce_isHiddenFile (const String& path) -{ -#if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - const ScopedAutoReleasePool pool; - NSNumber* hidden = nil; - NSError* err = nil; - - return [[NSURL fileURLWithPath: juceStringToNS (path)] - getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err] - && [hidden boolValue]; -#else - #if JUCE_IOS - return File (path).getFileName().startsWithChar ('.'); - #else - FSRef ref; - LSItemInfoRecord info; - - return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr - && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr - && (info.flags & kLSItemInfoIsInvisible) != 0; - #endif -#endif -} - bool File::isHidden() const { return juce_isHiddenFile (getFullPathName()); } -#if JUCE_IOS -static const String getIOSSystemLocation (NSSearchPathDirectory type) -{ - return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES) - objectAtIndex: 0]); -} -#endif - //============================================================================== const char* juce_Argv0 = 0; // referenced from juce_Application.cpp diff --git a/src/native/mac/juce_mac_MainMenu.mm b/src/native/mac/juce_mac_MainMenu.mm index f8f5964676..de7c058fb0 100644 --- a/src/native/mac/juce_mac_MainMenu.mm +++ b/src/native/mac/juce_mac_MainMenu.mm @@ -422,88 +422,90 @@ END_JUCE_NAMESPACE BEGIN_JUCE_NAMESPACE //============================================================================== -static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, - const PopupMenu* extraItems) +namespace MainMenuHelpers { - if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0) + NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems) { - PopupMenu::MenuItemIterator iter (*extraItems); + if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0) + { + PopupMenu::MenuItemIterator iter (*extraItems); - while (iter.next()) - JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1); + while (iter.next()) + JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1); + + [menu addItem: [NSMenuItem separatorItem]]; + } + + NSMenuItem* item; + + // Services... + item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil) + action: nil keyEquivalent: @""]; + [menu addItem: item]; + [item release]; + NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"]; + [menu setSubmenu: servicesMenu forItem: item]; + [NSApp setServicesMenu: servicesMenu]; + [servicesMenu release]; + [menu addItem: [NSMenuItem separatorItem]]; + + // Hide + Show stuff... + item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName) + action: @selector (hide:) keyEquivalent: @"h"]; + [item setTarget: NSApp]; + [menu addItem: item]; + [item release]; + + item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil) + action: @selector (hideOtherApplications:) keyEquivalent: @"h"]; + [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask]; + [item setTarget: NSApp]; + [menu addItem: item]; + [item release]; + + item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil) + action: @selector (unhideAllApplications:) keyEquivalent: @""]; + [item setTarget: NSApp]; + [menu addItem: item]; + [item release]; [menu addItem: [NSMenuItem separatorItem]]; + + // Quit item.... + item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName) + action: @selector (terminate:) keyEquivalent: @"q"]; + + [item setTarget: NSApp]; + [menu addItem: item]; + [item release]; + + return menu; } - NSMenuItem* item; - - // Services... - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil) - action: nil keyEquivalent: @""]; - [menu addItem: item]; - [item release]; - NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"]; - [menu setSubmenu: servicesMenu forItem: item]; - [NSApp setServicesMenu: servicesMenu]; - [servicesMenu release]; - [menu addItem: [NSMenuItem separatorItem]]; - - // Hide + Show stuff... - item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName) - action: @selector (hide:) keyEquivalent: @"h"]; - [item setTarget: NSApp]; - [menu addItem: item]; - [item release]; - - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil) - action: @selector (hideOtherApplications:) keyEquivalent: @"h"]; - [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask]; - [item setTarget: NSApp]; - [menu addItem: item]; - [item release]; - - item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil) - action: @selector (unhideAllApplications:) keyEquivalent: @""]; - [item setTarget: NSApp]; - [menu addItem: item]; - [item release]; - - [menu addItem: [NSMenuItem separatorItem]]; - - // Quit item.... - item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName) - action: @selector (terminate:) keyEquivalent: @"q"]; - - [item setTarget: NSApp]; - [menu addItem: item]; - [item release]; - - return menu; -} - -// Since our app has no NIB, this initialises a standard app menu... -static void rebuildMainMenu (const PopupMenu* extraItems) -{ - // this can't be used in a plugin! - jassert (JUCEApplication::isStandaloneApp()); - - if (JUCEApplication::getInstance() != 0) + // Since our app has no NIB, this initialises a standard app menu... + void rebuildMainMenu (const PopupMenu* extraItems) { - const ScopedAutoReleasePool pool; + // this can't be used in a plugin! + jassert (JUCEApplication::isStandaloneApp()); - NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"]; - NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""]; + if (JUCEApplication::getInstance() != 0) + { + const ScopedAutoReleasePool pool; - NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"]; + NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"]; + NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""]; - [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu]; - [mainMenu setSubmenu: appMenu forItem: item]; + NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"]; - [NSApp setMainMenu: mainMenu]; - createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems); + [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu]; + [mainMenu setSubmenu: appMenu forItem: item]; - [appMenu release]; - [mainMenu release]; + [NSApp setMainMenu: mainMenu]; + MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems); + + [appMenu release]; + [mainMenu release]; + } } } @@ -531,7 +533,7 @@ void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel, } } - rebuildMainMenu (extraAppleMenuItems); + MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems); if (newMenuBarModel != 0) newMenuBarModel->menuItemsChanged(); @@ -546,7 +548,7 @@ MenuBarModel* MenuBarModel::getMacMainMenu() void juce_initialiseMacMainMenu() { if (JuceMainMenuHandler::instance == 0) - rebuildMainMenu (0); + MainMenuHelpers::rebuildMainMenu (0); } diff --git a/src/native/mac/juce_mac_MessageManager.mm b/src/native/mac/juce_mac_MessageManager.mm index ed0a3b1483..a3654e9b89 100644 --- a/src/native/mac/juce_mac_MessageManager.mm +++ b/src/native/mac/juce_mac_MessageManager.mm @@ -346,88 +346,91 @@ void MessageManager::stopDispatchLoop() [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1]; } -static bool isEventBlockedByModalComps (NSEvent* e) +namespace { - if (Component::getNumCurrentlyModalComponents() == 0) - return false; - - NSWindow* const w = [e window]; - if (w == 0 || [w worksWhenModal]) - return false; - - bool isKey = false, isInputAttempt = false; - - switch ([e type]) + bool isEventBlockedByModalComps (NSEvent* e) { - case NSKeyDown: - case NSKeyUp: - isKey = isInputAttempt = true; - break; - - case NSLeftMouseDown: - case NSRightMouseDown: - case NSOtherMouseDown: - isInputAttempt = true; - break; - - case NSLeftMouseDragged: - case NSRightMouseDragged: - case NSLeftMouseUp: - case NSRightMouseUp: - case NSOtherMouseUp: - case NSOtherMouseDragged: - if (Desktop::getInstance().getDraggingMouseSource(0) != 0) - return false; - break; - - case NSMouseMoved: - case NSMouseEntered: - case NSMouseExited: - case NSCursorUpdate: - case NSScrollWheel: - case NSTabletPoint: - case NSTabletProximity: - break; - - default: + if (Component::getNumCurrentlyModalComponents() == 0) return false; - } - for (int i = ComponentPeer::getNumPeers(); --i >= 0;) - { - ComponentPeer* const peer = ComponentPeer::getPeer (i); - NSView* const compView = (NSView*) peer->getNativeHandle(); + NSWindow* const w = [e window]; + if (w == 0 || [w worksWhenModal]) + return false; - if ([compView window] == w) + bool isKey = false, isInputAttempt = false; + + switch ([e type]) { - if (isKey) - { - if (compView == [w firstResponder]) - return false; - } - else - { - NSViewComponentPeer* nsViewPeer = dynamic_cast (peer); + case NSKeyDown: + case NSKeyUp: + isKey = isInputAttempt = true; + break; - if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow) - ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)) - : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds])) + case NSLeftMouseDown: + case NSRightMouseDown: + case NSOtherMouseDown: + isInputAttempt = true; + break; + + case NSLeftMouseDragged: + case NSRightMouseDragged: + case NSLeftMouseUp: + case NSRightMouseUp: + case NSOtherMouseUp: + case NSOtherMouseDragged: + if (Desktop::getInstance().getDraggingMouseSource(0) != 0) return false; + break; + + case NSMouseMoved: + case NSMouseEntered: + case NSMouseExited: + case NSCursorUpdate: + case NSScrollWheel: + case NSTabletPoint: + case NSTabletProximity: + break; + + default: + return false; + } + + for (int i = ComponentPeer::getNumPeers(); --i >= 0;) + { + ComponentPeer* const peer = ComponentPeer::getPeer (i); + NSView* const compView = (NSView*) peer->getNativeHandle(); + + if ([compView window] == w) + { + if (isKey) + { + if (compView == [w firstResponder]) + return false; + } + else + { + NSViewComponentPeer* nsViewPeer = dynamic_cast (peer); + + if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow) + ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)) + : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds])) + return false; + } } } + + if (isInputAttempt) + { + if (! [NSApp isActive]) + [NSApp activateIgnoringOtherApps: YES]; + + Component* const modal = Component::getCurrentlyModalComponent (0); + if (modal != 0) + modal->inputAttemptWhenModal(); + } + + return true; } - - if (isInputAttempt) - { - if (! [NSApp isActive]) - [NSApp activateIgnoringOtherApps: YES]; - - Component* const modal = Component::getCurrentlyModalComponent (0); - if (modal != 0) - modal->inputAttemptWhenModal(); - } - - return true; } bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor) diff --git a/src/native/mac/juce_mac_MouseCursor.mm b/src/native/mac/juce_mac_MouseCursor.mm index 89abae489a..5541e87193 100644 --- a/src/native/mac/juce_mac_MouseCursor.mm +++ b/src/native/mac/juce_mac_MouseCursor.mm @@ -44,7 +44,7 @@ namespace MouseCursorHelpers static void* fromWebKitFile (const char* filename, float hx, float hy) { FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename); - BufferedInputStream buf (&fileStream, 4096, false); + BufferedInputStream buf (fileStream, 4096); PNGImageFormat pngFormat; Image im (pngFormat.decodeImage (buf)); diff --git a/src/native/mac/juce_mac_Strings.mm b/src/native/mac/juce_mac_Strings.mm index c910ae4071..1d615dd707 100644 --- a/src/native/mac/juce_mac_Strings.mm +++ b/src/native/mac/juce_mac_Strings.mm @@ -28,26 +28,28 @@ #if JUCE_INCLUDED_FILE //============================================================================== -static const String nsStringToJuce (NSString* s) +namespace { - return String::fromUTF8 ([s UTF8String]); -} + const String nsStringToJuce (NSString* s) + { + return String::fromUTF8 ([s UTF8String]); + } -static NSString* juceStringToNS (const String& s) -{ - return [NSString stringWithUTF8String: s.toUTF8()]; -} + NSString* juceStringToNS (const String& s) + { + return [NSString stringWithUTF8String: s.toUTF8()]; + } + //============================================================================== + const String convertUTF16ToString (const UniChar* utf16) + { + String s; -//============================================================================== -static const String convertUTF16ToString (const UniChar* utf16) -{ - String s; + while (*utf16 != 0) + s += (juce_wchar) *utf16++; - while (*utf16 != 0) - s += (juce_wchar) *utf16++; - - return s; + return s; + } } const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString) diff --git a/src/native/windows/juce_win32_ASIO.cpp b/src/native/windows/juce_win32_ASIO.cpp index bc6005a6dd..d772d9f8ce 100644 --- a/src/native/windows/juce_win32_ASIO.cpp +++ b/src/native/windows/juce_win32_ASIO.cpp @@ -32,6 +32,7 @@ //============================================================================== // #define ASIO_DEBUGGING 1 +#undef log #if ASIO_DEBUGGING #define log(a) { Logger::writeToLog (a); DBG (a) } #else @@ -46,24 +47,29 @@ #define JUCE_ASIOCALLBACK __cdecl //============================================================================== -#if ASIO_DEBUGGING -static void logError (const String& context, long error) +namespace ASIODebugging { - String err ("unknown error"); + #if ASIO_DEBUGGING + static void log (const String& context, long error) + { + String err ("unknown error"); - if (error == ASE_NotPresent) err = "Not Present"; - else if (error == ASE_HWMalfunction) err = "Hardware Malfunction"; - else if (error == ASE_InvalidParameter) err = "Invalid Parameter"; - else if (error == ASE_InvalidMode) err = "Invalid Mode"; - else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing"; - else if (error == ASE_NoClock) err = "No Clock"; - else if (error == ASE_NoMemory) err = "Out of memory"; + if (error == ASE_NotPresent) err = "Not Present"; + else if (error == ASE_HWMalfunction) err = "Hardware Malfunction"; + else if (error == ASE_InvalidParameter) err = "Invalid Parameter"; + else if (error == ASE_InvalidMode) err = "Invalid Mode"; + else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing"; + else if (error == ASE_NoClock) err = "No Clock"; + else if (error == ASE_NoMemory) err = "Out of memory"; - log ("!!error: " + context + " - " + err); + log ("!!error: " + context + " - " + err); + } + + #define logError(a, b) ASIODebugging::log ((a), (b)) + #else + #define logError(a, b) {} + #endif } -#else - #define logError(a, b) {} -#endif //============================================================================== class ASIOAudioIODevice; @@ -1874,6 +1880,7 @@ AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name, return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading); } +#undef logError #undef log #endif diff --git a/src/native/windows/juce_win32_AudioCDReader.cpp b/src/native/windows/juce_win32_AudioCDReader.cpp index 68c572da1c..8b4df80e5a 100644 --- a/src/native/windows/juce_win32_AudioCDReader.cpp +++ b/src/native/windows/juce_win32_AudioCDReader.cpp @@ -659,7 +659,7 @@ static bool usingScsi = false; static bool initialised = false; -static bool InitialiseCDRipper() +bool InitialiseCDRipper() { if (! initialised) { @@ -695,7 +695,7 @@ static bool InitialiseCDRipper() return true; } -static void DeinitialiseCDRipper() +void DeinitialiseCDRipper() { if (winAspiLib != 0) { @@ -709,7 +709,7 @@ static void DeinitialiseCDRipper() } //============================================================================== -static HANDLE CreateSCSIDeviceHandle (char driveLetter) +HANDLE CreateSCSIDeviceHandle (char driveLetter) { TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 }; @@ -733,10 +733,8 @@ static HANDLE CreateSCSIDeviceHandle (char driveLetter) return h; } -static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, - const char driveLetter, - HANDLE& deviceHandle, - const bool retryOnFailure = true) +DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, const char driveLetter, + HANDLE& deviceHandle, const bool retryOnFailure = true) { SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s; zerostruct (s); @@ -1363,7 +1361,7 @@ bool CDDeviceHandle::testController (const int type, //============================================================================== -static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun) +void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun) { HANDLE event = CreateEvent (0, TRUE, FALSE, 0); @@ -1403,8 +1401,7 @@ static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun) } } -static int FindCDDevices (CDDeviceInfo* const list, - int maxItems) +int FindCDDevices (CDDeviceInfo* const list, int maxItems) { int count = 0; @@ -1590,7 +1587,7 @@ struct CDDeviceWrapper }; //============================================================================== -static int getAddressOf (const TOCTRACK* const t) +int getAddressOf (const TOCTRACK* const t) { return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) + (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]); @@ -1599,7 +1596,7 @@ static int getAddressOf (const TOCTRACK* const t) static const int samplesPerFrame = 44100 / 75; static const int bytesPerFrame = samplesPerFrame * 4; -static CDDeviceHandle* openHandle (const CDDeviceInfo* const device) +CDDeviceHandle* openHandle (const CDDeviceInfo* const device) { SRB_GDEVBlock s; zerostruct (s); @@ -2015,61 +2012,64 @@ void AudioCDReader::ejectDisk() #if JUCE_USE_CDBURNER //============================================================================== -static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master) +namespace CDBurnerHelpers { - CoInitialize (0); - - IDiscMaster* dm; - IDiscRecorder* result = 0; - - if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0, - CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, - IID_IDiscMaster, - (void**) &dm))) + IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master) { - if (SUCCEEDED (dm->Open())) + CoInitialize (0); + + IDiscMaster* dm; + IDiscRecorder* result = 0; + + if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0, + CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, + IID_IDiscMaster, + (void**) &dm))) { - IEnumDiscRecorders* drEnum = 0; - - if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum))) + if (SUCCEEDED (dm->Open())) { - IDiscRecorder* dr = 0; - DWORD dummy; - int index = 0; + IEnumDiscRecorders* drEnum = 0; - while (drEnum->Next (1, &dr, &dummy) == S_OK) + if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum))) { - if (indexToOpen == index) - { - result = dr; - break; - } - else if (list != 0) - { - BSTR path; + IDiscRecorder* dr = 0; + DWORD dummy; + int index = 0; - if (SUCCEEDED (dr->GetPath (&path))) - list->add ((const WCHAR*) path); + while (drEnum->Next (1, &dr, &dummy) == S_OK) + { + if (indexToOpen == index) + { + result = dr; + break; + } + else if (list != 0) + { + BSTR path; + + if (SUCCEEDED (dr->GetPath (&path))) + list->add ((const WCHAR*) path); + } + + ++index; + dr->Release(); } - ++index; - dr->Release(); + drEnum->Release(); } - drEnum->Release(); + if (master == 0) + dm->Close(); } - if (master == 0) - dm->Close(); + if (master != 0) + *master = dm; + else + dm->Release(); } - if (master != 0) - *master = dm; - else - dm->Release(); + return result; } - - return result; } //============================================================================== @@ -2219,7 +2219,7 @@ public: AudioCDBurner::AudioCDBurner (const int deviceIndex) { IDiscMaster* discMaster = 0; - IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster); + IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster); if (discRecorder != 0) pimpl = new Pimpl (*this, discMaster, discRecorder); @@ -2234,7 +2234,7 @@ AudioCDBurner::~AudioCDBurner() const StringArray AudioCDBurner::findAvailableDevices() { StringArray devs; - enumCDBurners (&devs, -1, 0); + CDBurnerHelpers::enumCDBurners (&devs, -1, 0); return devs; } diff --git a/src/native/windows/juce_win32_CameraDevice.cpp b/src/native/windows/juce_win32_CameraDevice.cpp index 09ec49a499..8e86ae3c55 100644 --- a/src/native/windows/juce_win32_CameraDevice.cpp +++ b/src/native/windows/juce_win32_CameraDevice.cpp @@ -759,65 +759,68 @@ void CameraDevice::removeListener (Listener* listenerToRemove) //============================================================================== -static ComSmartPtr enumerateCameras (StringArray* const names, - const int deviceIndexToOpen, - String& name) +namespace { - int index = 0; - ComSmartPtr result; - - ComSmartPtr pDevEnum; - HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum); - - if (SUCCEEDED (hr)) + ComSmartPtr enumerateCameras (StringArray* const names, + const int deviceIndexToOpen, + String& name) { - ComSmartPtr enumerator; - hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0); + int index = 0; + ComSmartPtr result; - if (SUCCEEDED (hr) && enumerator != 0) + ComSmartPtr pDevEnum; + HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum); + + if (SUCCEEDED (hr)) { - ComSmartPtr moniker; - ULONG fetched; + ComSmartPtr enumerator; + hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0); - while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK) + if (SUCCEEDED (hr) && enumerator != 0) { - ComSmartPtr captureFilter; - hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress()); + ComSmartPtr moniker; + ULONG fetched; - if (SUCCEEDED (hr)) + while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK) { - ComSmartPtr propertyBag; - hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress()); + ComSmartPtr captureFilter; + hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress()); if (SUCCEEDED (hr)) { - VARIANT var; - var.vt = VT_BSTR; - - hr = propertyBag->Read (_T("FriendlyName"), &var, 0); - propertyBag = 0; + ComSmartPtr propertyBag; + hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress()); if (SUCCEEDED (hr)) { - if (names != 0) - names->add (var.bstrVal); + VARIANT var; + var.vt = VT_BSTR; - if (index == deviceIndexToOpen) + hr = propertyBag->Read (_T("FriendlyName"), &var, 0); + propertyBag = 0; + + if (SUCCEEDED (hr)) { - name = var.bstrVal; - result = captureFilter; - break; - } + if (names != 0) + names->add (var.bstrVal); - ++index; + if (index == deviceIndexToOpen) + { + name = var.bstrVal; + result = captureFilter; + break; + } + + ++index; + } } } } } } - } - return result; + return result; + } } const StringArray CameraDevice::getAvailableDevices() diff --git a/src/native/windows/juce_win32_DirectSound.cpp b/src/native/windows/juce_win32_DirectSound.cpp index 4b17a9f08b..7db3ade9cc 100644 --- a/src/native/windows/juce_win32_DirectSound.cpp +++ b/src/native/windows/juce_win32_DirectSound.cpp @@ -137,89 +137,92 @@ DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown) //============================================================================== BEGIN_JUCE_NAMESPACE -static const String getDSErrorMessage (HRESULT hr) +namespace { - const char* result = 0; - - switch (hr) + const String getDSErrorMessage (HRESULT hr) { - case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break; - case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break; - case E_INVALIDARG: result = "Invalid parameter"; break; - case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break; - case E_FAIL: result = "Generic error"; break; - case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break; - case E_OUTOFMEMORY: result = "Out of memory"; break; - case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break; - case E_NOTIMPL: result = "Unsupported function"; break; - case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break; - case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break; - case CLASS_E_NOAGGREGATION: result = "No aggregation"; break; - case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break; - case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break; - case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break; - case E_NOINTERFACE: result = "No interface"; break; - case S_OK: result = "No error"; break; - default: return "Unknown error: " + String ((int) hr); + const char* result = 0; + + switch (hr) + { + case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break; + case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break; + case E_INVALIDARG: result = "Invalid parameter"; break; + case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break; + case E_FAIL: result = "Generic error"; break; + case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break; + case E_OUTOFMEMORY: result = "Out of memory"; break; + case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break; + case E_NOTIMPL: result = "Unsupported function"; break; + case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break; + case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break; + case CLASS_E_NOAGGREGATION: result = "No aggregation"; break; + case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break; + case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break; + case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break; + case E_NOINTERFACE: result = "No interface"; break; + case S_OK: result = "No error"; break; + default: return "Unknown error: " + String ((int) hr); + } + + return result; } - return result; -} + //============================================================================== + #define DS_DEBUGGING 1 -//============================================================================== -#define DS_DEBUGGING 1 + #ifdef DS_DEBUGGING + #define CATCH JUCE_CATCH_EXCEPTION + #undef log + #define log(a) Logger::writeToLog(a); + #undef logError + #define logError(a) logDSError(a, __LINE__); -#ifdef DS_DEBUGGING - #define CATCH JUCE_CATCH_EXCEPTION - #undef log - #define log(a) Logger::writeToLog(a); - #undef logError - #define logError(a) logDSError(a, __LINE__); - - static void logDSError (HRESULT hr, int lineNum) - { - if (hr != S_OK) + static void logDSError (HRESULT hr, int lineNum) { - String error ("DS error at line "); - error << lineNum << " - " << getDSErrorMessage (hr); - log (error); + if (hr != S_OK) + { + String error ("DS error at line "); + error << lineNum << " - " << getDSErrorMessage (hr); + log (error); + } + } + #else + #define CATCH JUCE_CATCH_ALL + #define log(a) + #define logError(a) + #endif + + //============================================================================== + #define DSOUND_FUNCTION(functionName, params) \ + typedef HRESULT (WINAPI *type##functionName) params; \ + static type##functionName ds##functionName = 0; + + #define DSOUND_FUNCTION_LOAD(functionName) \ + ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \ + jassert (ds##functionName != 0); + + typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID); + typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID); + + DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN)) + DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN)) + DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID)) + DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID)) + + void initialiseDSoundFunctions() + { + if (dsDirectSoundCreate == 0) + { + HMODULE h = LoadLibraryA ("dsound.dll"); + + DSOUND_FUNCTION_LOAD (DirectSoundCreate) + DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate) + DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW) + DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW) } } -#else - #define CATCH JUCE_CATCH_ALL - #define log(a) - #define logError(a) -#endif - -//============================================================================== -#define DSOUND_FUNCTION(functionName, params) \ - typedef HRESULT (WINAPI *type##functionName) params; \ - static type##functionName ds##functionName = 0; - -#define DSOUND_FUNCTION_LOAD(functionName) \ - ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \ - jassert (ds##functionName != 0); - -typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID); -typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID); - -DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN)) -DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN)) -DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID)) -DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID)) - -static void initialiseDSoundFunctions() -{ - if (dsDirectSoundCreate == 0) - { - HMODULE h = LoadLibraryA ("dsound.dll"); - - DSOUND_FUNCTION_LOAD (DirectSoundCreate) - DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate) - DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW) - DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW) - } } //============================================================================== diff --git a/src/native/windows/juce_win32_Files.cpp b/src/native/windows/juce_win32_Files.cpp index 15655494b3..f1a6527973 100644 --- a/src/native/windows/juce_win32_Files.cpp +++ b/src/native/windows/juce_win32_Files.cpp @@ -41,6 +41,56 @@ #define INVALID_FILE_ATTRIBUTES ((DWORD) -1) #endif +//============================================================================== +namespace WindowsFileHelpers +{ + int64 fileTimeToTime (const FILETIME* const ft) + { + static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails! + + return (reinterpret_cast (ft)->QuadPart - literal64bit (116444736000000000)) / 10000; + } + + void timeToFileTime (const int64 time, FILETIME* const ft) + { + reinterpret_cast (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000); + } + + const String getDriveFromPath (const String& path) + { + if (path.isNotEmpty() && path[1] == ':') + return path.substring (0, 2) + '\\'; + + return path; + } + + int64 getDiskSpaceInfo (const String& path, const bool total) + { + ULARGE_INTEGER spc, tot, totFree; + + if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree)) + return total ? (int64) tot.QuadPart + : (int64) spc.QuadPart; + + return 0; + } + + unsigned int getWindowsDriveType (const String& path) + { + return GetDriveType (getDriveFromPath (path)); + } + + const File getSpecialFolderPath (int type) + { + WCHAR path [MAX_PATH + 256]; + + if (SHGetSpecialFolderPath (0, path, type, FALSE)) + return File (String (path)); + + return File::nonexistent; + } +} + //============================================================================== const juce_wchar File::separator = '\\'; const String File::separatorString ("\\"); @@ -236,21 +286,9 @@ int64 File::getSize() const return 0; } -//============================================================================== -static int64 fileTimeToTime (const FILETIME* const ft) -{ - static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails! - - return (reinterpret_cast (ft)->QuadPart - literal64bit (116444736000000000)) / 10000; -} - -static void timeToFileTime (const int64 time, FILETIME* const ft) -{ - reinterpret_cast (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000); -} - void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const { + using namespace WindowsFileHelpers; WIN32_FILE_ATTRIBUTE_DATA attributes; if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes)) @@ -267,6 +305,8 @@ void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const { + using namespace WindowsFileHelpers; + bool ok = false; HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); @@ -315,18 +355,10 @@ void File::findFileSystemRoots (Array& destArray) } //============================================================================== -static const String getDriveFromPath (const String& path) -{ - if (path.isNotEmpty() && path[1] == ':') - return path.substring (0, 2) + '\\'; - - return path; -} - const String File::getVolumeLabel() const { TCHAR dest[64]; - if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest, + if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest, numElementsInArray (dest), 0, 0, 0, 0, 0)) dest[0] = 0; @@ -338,43 +370,27 @@ int File::getVolumeSerialNumber() const TCHAR dest[64]; DWORD serialNum; - if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest, + if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest, numElementsInArray (dest), &serialNum, 0, 0, 0, 0)) return 0; return (int) serialNum; } -static int64 getDiskSpaceInfo (const String& path, const bool total) -{ - ULARGE_INTEGER spc, tot, totFree; - - if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree)) - return total ? (int64) tot.QuadPart - : (int64) spc.QuadPart; - - return 0; -} - int64 File::getBytesFreeOnVolume() const { - return getDiskSpaceInfo (getFullPathName(), false); + return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false); } int64 File::getVolumeTotalSize() const { - return getDiskSpaceInfo (getFullPathName(), true); + return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true); } //============================================================================== -static unsigned int getWindowsDriveType (const String& path) -{ - return GetDriveType (getDriveFromPath (path)); -} - bool File::isOnCDRomDrive() const { - return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM; + return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM; } bool File::isOnHardDisk() const @@ -382,7 +398,7 @@ bool File::isOnHardDisk() const if (fullPath.isEmpty()) return false; - const unsigned int n = getWindowsDriveType (getFullPathName()); + const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName()); if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':') return n != DRIVE_REMOVABLE; @@ -395,7 +411,7 @@ bool File::isOnRemovableDrive() const if (fullPath.isEmpty()) return false; - const unsigned int n = getWindowsDriveType (getFullPathName()); + const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName()); return n == DRIVE_CDROM || n == DRIVE_REMOTE @@ -404,16 +420,6 @@ bool File::isOnRemovableDrive() const } //============================================================================== -static const File juce_getSpecialFolderPath (int type) -{ - WCHAR path [MAX_PATH + 256]; - - if (SHGetSpecialFolderPath (0, path, type, FALSE)) - return File (String (path)); - - return File::nonexistent; -} - const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type) { int csidlType = 0; @@ -462,7 +468,7 @@ const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType typ return File::nonexistent; } - return juce_getSpecialFolderPath (csidlType); + return WindowsFileHelpers::getSpecialFolderPath (csidlType); } //============================================================================== @@ -559,6 +565,7 @@ public: bool* const isDir, bool* const isHidden, int64* const fileSize, Time* const modTime, Time* const creationTime, bool* const isReadOnly) { + using namespace WindowsFileHelpers; WIN32_FIND_DATA findData; if (handle == INVALID_HANDLE_VALUE) diff --git a/src/native/windows/juce_win32_PlatformUtils.cpp b/src/native/windows/juce_win32_PlatformUtils.cpp index 493ed0bb38..86ec069995 100644 --- a/src/native/windows/juce_win32_PlatformUtils.cpp +++ b/src/native/windows/juce_win32_PlatformUtils.cpp @@ -29,44 +29,45 @@ //============================================================================== -static HKEY findKeyForPath (String name, - const bool createForWriting, - String& valueName) +namespace { - HKEY rootKey = 0; - - if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\")) - rootKey = HKEY_CURRENT_USER; - else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\")) - rootKey = HKEY_LOCAL_MACHINE; - else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\")) - rootKey = HKEY_CLASSES_ROOT; - - if (rootKey != 0) + HKEY findKeyForPath (String name, const bool createForWriting, String& valueName) { - name = name.substring (name.indexOfChar ('\\') + 1); + HKEY rootKey = 0; - const int lastSlash = name.lastIndexOfChar ('\\'); - valueName = name.substring (lastSlash + 1); - name = name.substring (0, lastSlash); + if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\")) + rootKey = HKEY_CURRENT_USER; + else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\")) + rootKey = HKEY_LOCAL_MACHINE; + else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\")) + rootKey = HKEY_CLASSES_ROOT; - HKEY key; - DWORD result; - - if (createForWriting) + if (rootKey != 0) { - if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE, - (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS) - return key; - } - else - { - if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS) - return key; + name = name.substring (name.indexOfChar ('\\') + 1); + + const int lastSlash = name.lastIndexOfChar ('\\'); + valueName = name.substring (lastSlash + 1); + name = name.substring (0, lastSlash); + + HKEY key; + DWORD result; + + if (createForWriting) + { + if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE, + (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS) + return key; + } + else + { + if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS) + return key; + } } + + return 0; } - - return 0; } const String PlatformUtilities::getRegistryValue (const String& regValuePath, diff --git a/src/native/windows/juce_win32_WASAPI.cpp b/src/native/windows/juce_win32_WASAPI.cpp index 8ba0b9d5e0..ed0f40d57f 100644 --- a/src/native/windows/juce_win32_WASAPI.cpp +++ b/src/native/windows/juce_win32_WASAPI.cpp @@ -35,7 +35,7 @@ namespace WasapiClasses { -static void logFailure (HRESULT hr) +void logFailure (HRESULT hr) { (void) hr; @@ -84,14 +84,14 @@ static void logFailure (HRESULT hr) #undef check -static bool check (HRESULT hr) +bool check (HRESULT hr) { logFailure (hr); return SUCCEEDED (hr); } //============================================================================== -static const String getDeviceID (IMMDevice* const device) +const String getDeviceID (IMMDevice* const device) { String s; WCHAR* deviceId = 0; @@ -105,7 +105,7 @@ static const String getDeviceID (IMMDevice* const device) return s; } -static EDataFlow getDataFlow (const ComSmartPtr& device) +EDataFlow getDataFlow (const ComSmartPtr& device) { EDataFlow flow = eRender; ComSmartPtr endPoint; @@ -115,18 +115,17 @@ static EDataFlow getDataFlow (const ComSmartPtr& device) return flow; } -static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw() +int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw() { return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001); } -static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw() +void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw() { memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE) : sizeof (WAVEFORMATEX)); } - //============================================================================== class WASAPIDeviceBase { @@ -393,7 +392,7 @@ public: const int samplesToDo = jmin (bufferSize, (int) reservoirSize); for (int i = 0; i < numDestBuffers; ++i) - converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo); + converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo); bufferSize -= samplesToDo; offset += samplesToDo; @@ -423,7 +422,7 @@ public: const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable); for (int i = 0; i < numDestBuffers; ++i) - converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo); + converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo); bufferSize -= samplesToDo; offset += samplesToDo; @@ -520,7 +519,7 @@ public: if (check (renderClient->GetBuffer (samplesToDo, &outputData))) { for (int i = 0; i < numSrcBuffers; ++i) - converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo); + converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo); renderClient->ReleaseBuffer (samplesToDo, 0); diff --git a/src/native/windows/juce_win32_Windowing.cpp b/src/native/windows/juce_win32_Windowing.cpp index 95197f2a63..a0a4e51e66 100644 --- a/src/native/windows/juce_win32_Windowing.cpp +++ b/src/native/windows/juce_win32_Windowing.cpp @@ -58,7 +58,6 @@ static HPALETTE palette = 0; static bool createPaletteIfNeeded = true; static bool shouldDeactivateTitleBar = true; -static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY); #define WM_TRAYNOTIFY WM_USER + 100 using ::abs; @@ -345,6 +344,101 @@ private: WindowsBitmapImage& operator= (const WindowsBitmapImage&); }; +namespace IconConverters +{ + const Image createImageFromHBITMAP (HBITMAP bitmap) + { + Image im; + + if (bitmap != 0) + { + BITMAP bm; + + if (GetObject (bitmap, sizeof (BITMAP), &bm) + && bm.bmWidth > 0 && bm.bmHeight > 0) + { + HDC tempDC = GetDC (0); + HDC dc = CreateCompatibleDC (tempDC); + ReleaseDC (0, tempDC); + + SelectObject (dc, bitmap); + + im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true); + Image::BitmapData imageData (im, true); + + for (int y = bm.bmHeight; --y >= 0;) + { + for (int x = bm.bmWidth; --x >= 0;) + { + COLORREF col = GetPixel (dc, x, y); + + imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col), + (uint8) GetGValue (col), + (uint8) GetBValue (col))); + } + } + + DeleteDC (dc); + } + } + + return im; + } + + const Image createImageFromHICON (HICON icon) + { + ICONINFO info; + + if (GetIconInfo (icon, &info)) + { + Image mask (createImageFromHBITMAP (info.hbmMask)); + Image image (createImageFromHBITMAP (info.hbmColor)); + + if (mask.isValid() && image.isValid()) + { + for (int y = image.getHeight(); --y >= 0;) + { + for (int x = image.getWidth(); --x >= 0;) + { + const float brightness = mask.getPixelAt (x, y).getBrightness(); + + if (brightness > 0.0f) + image.multiplyAlphaAt (x, y, 1.0f - brightness); + } + } + + return image; + } + } + + return Image::null; + } + + HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) + { + WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true); + Image bitmap (nativeBitmap); + + { + Graphics g (bitmap); + g.drawImageAt (image, 0, 0); + } + + HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0); + + ICONINFO info; + info.fIcon = isIcon; + info.xHotspot = hotspotX; + info.yHotspot = hotspotY; + info.hbmMask = mask; + info.hbmColor = nativeBitmap->hBitmap; + + HICON hi = CreateIconIndirect (&info); + DeleteObject (mask); + return hi; + } +} + //============================================================================== long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp @@ -376,14 +470,6 @@ bool KeyPress::isKeyCurrentlyDown (const int keyCode) return (GetKeyState (k) & 0x8000) != 0; } -static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData) -{ - if (MessageManager::getInstance()->currentThreadHasLockedMessageManager()) - return callback (userData); - else - return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData); -} - //============================================================================== class Win32ComponentPeer : public ComponentPeer { @@ -794,7 +880,7 @@ public: { if (image.isValid()) { - HICON hicon = createHICONFromImage (image, TRUE, 0, 0); + HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0); if (taskBarIcon == 0) { @@ -1138,7 +1224,7 @@ private: void setIcon (const Image& newIcon) { - HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0); + HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0); if (hicon != 0) { @@ -1772,6 +1858,14 @@ public: } private: + static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData) + { + if (MessageManager::getInstance()->currentThreadHasLockedMessageManager()) + return callback (userData); + else + return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData); + } + static const Point getPointFromLParam (LPARAM lParam) throw() { return Point (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam)); @@ -2480,98 +2574,6 @@ void juce_updateMultiMonitorInfo (Array >& monitorCoords, const } //============================================================================== -static const Image createImageFromHBITMAP (HBITMAP bitmap) -{ - Image im; - - if (bitmap != 0) - { - BITMAP bm; - - if (GetObject (bitmap, sizeof (BITMAP), &bm) - && bm.bmWidth > 0 && bm.bmHeight > 0) - { - HDC tempDC = GetDC (0); - HDC dc = CreateCompatibleDC (tempDC); - ReleaseDC (0, tempDC); - - SelectObject (dc, bitmap); - - im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true); - Image::BitmapData imageData (im, true); - - for (int y = bm.bmHeight; --y >= 0;) - { - for (int x = bm.bmWidth; --x >= 0;) - { - COLORREF col = GetPixel (dc, x, y); - - imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col), - (uint8) GetGValue (col), - (uint8) GetBValue (col))); - } - } - - DeleteDC (dc); - } - } - - return im; -} - -static const Image createImageFromHICON (HICON icon) -{ - ICONINFO info; - - if (GetIconInfo (icon, &info)) - { - Image mask (createImageFromHBITMAP (info.hbmMask)); - Image image (createImageFromHBITMAP (info.hbmColor)); - - if (mask.isValid() && image.isValid()) - { - for (int y = image.getHeight(); --y >= 0;) - { - for (int x = image.getWidth(); --x >= 0;) - { - const float brightness = mask.getPixelAt (x, y).getBrightness(); - - if (brightness > 0.0f) - image.multiplyAlphaAt (x, y, 1.0f - brightness); - } - } - - return image; - } - } - - return Image::null; -} - -static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) -{ - WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true); - Image bitmap (nativeBitmap); - - { - Graphics g (bitmap); - g.drawImageAt (image, 0, 0); - } - - HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0); - - ICONINFO info; - info.fIcon = isIcon; - info.xHotspot = hotspotX; - info.yHotspot = hotspotY; - info.hbmMask = mask; - info.hbmColor = nativeBitmap->hBitmap; - - HICON hi = CreateIconIndirect (&info); - DeleteObject (mask); - return hi; -} - const Image juce_createIconForFile (const File& file) { Image image; @@ -2585,7 +2587,7 @@ const Image juce_createIconForFile (const File& file) if (icon != 0) { - image = createImageFromHICON (icon); + image = IconConverters::createImageFromHICON (icon); DestroyIcon (icon); } @@ -2608,7 +2610,7 @@ void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, hotspotY = (hotspotY * maxH) / image.getHeight(); } - return createHICONFromImage (im, FALSE, hotspotX, hotspotY); + return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY); } void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) diff --git a/src/text/juce_CharacterFunctions.cpp b/src/text/juce_CharacterFunctions.cpp index 83cf8b910d..fcc56840ed 100644 --- a/src/text/juce_CharacterFunctions.cpp +++ b/src/text/juce_CharacterFunctions.cpp @@ -477,150 +477,153 @@ int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw() } //============================================================================== -static double juce_mulexp10 (const double value, int exponent) throw() +namespace { - if (exponent == 0) - return value; - - if (value == 0) - return 0; - - const bool negative = (exponent < 0); - if (negative) - exponent = -exponent; - - double result = 1.0, power = 10.0; - for (int bit = 1; exponent != 0; bit <<= 1) + double juce_mulexp10 (const double value, int exponent) throw() { - if ((exponent & bit) != 0) + if (exponent == 0) + return value; + + if (value == 0) + return 0; + + const bool negative = (exponent < 0); + if (negative) + exponent = -exponent; + + double result = 1.0, power = 10.0; + for (int bit = 1; exponent != 0; bit <<= 1) { - exponent ^= bit; - result *= power; - if (exponent == 0) - break; - } - power *= power; - } - - return negative ? (value / result) : (value * result); -} - -template -double juce_atof (const CharType* const original) throw() -{ - double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 }; - int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 }; - int exponent = 0, decPointIndex = 0, digit = 0; - int lastDigit = 0, numSignificantDigits = 0; - bool isNegative = false, digitsFound = false; - const int maxSignificantDigits = 15 + 2; - - const CharType* s = original; - while (CharacterFunctions::isWhitespace (*s)) - ++s; - - switch (*s) - { - case '-': isNegative = true; // fall-through.. - case '+': ++s; - } - - if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I') - return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF - - for (;;) - { - if (CharacterFunctions::isDigit (*s)) - { - lastDigit = digit; - digit = *s++ - '0'; - digitsFound = true; - - if (decPointIndex != 0) - exponentAdjustment[1]++; - - if (numSignificantDigits == 0 && digit == 0) - continue; - - if (++numSignificantDigits > maxSignificantDigits) + if ((exponent & bit) != 0) { - if (digit > 5) - ++accumulator [decPointIndex]; - else if (digit == 5 && (lastDigit & 1) != 0) - ++accumulator [decPointIndex]; + exponent ^= bit; + result *= power; + if (exponent == 0) + break; + } + power *= power; + } - if (decPointIndex > 0) - exponentAdjustment[1]--; - else - exponentAdjustment[0]++; + return negative ? (value / result) : (value * result); + } - while (CharacterFunctions::isDigit (*s)) + template + double juce_atof (const CharType* const original) throw() + { + double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 }; + int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 }; + int exponent = 0, decPointIndex = 0, digit = 0; + int lastDigit = 0, numSignificantDigits = 0; + bool isNegative = false, digitsFound = false; + const int maxSignificantDigits = 15 + 2; + + const CharType* s = original; + while (CharacterFunctions::isWhitespace (*s)) + ++s; + + switch (*s) + { + case '-': isNegative = true; // fall-through.. + case '+': ++s; + } + + if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I') + return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF + + for (;;) + { + if (CharacterFunctions::isDigit (*s)) + { + lastDigit = digit; + digit = *s++ - '0'; + digitsFound = true; + + if (decPointIndex != 0) + exponentAdjustment[1]++; + + if (numSignificantDigits == 0 && digit == 0) + continue; + + if (++numSignificantDigits > maxSignificantDigits) { - ++s; - if (decPointIndex == 0) + if (digit > 5) + ++accumulator [decPointIndex]; + else if (digit == 5 && (lastDigit & 1) != 0) + ++accumulator [decPointIndex]; + + if (decPointIndex > 0) + exponentAdjustment[1]--; + else exponentAdjustment[0]++; + + while (CharacterFunctions::isDigit (*s)) + { + ++s; + if (decPointIndex == 0) + exponentAdjustment[0]++; + } + } + else + { + const double maxAccumulatorValue = (double) ((std::numeric_limits::max() - 9) / 10); + if (accumulator [decPointIndex] > maxAccumulatorValue) + { + result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex]) + + accumulator [decPointIndex]; + accumulator [decPointIndex] = 0; + exponentAccumulator [decPointIndex] = 0; + } + + accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit; + exponentAccumulator [decPointIndex]++; + } + } + else if (decPointIndex == 0 && *s == '.') + { + ++s; + decPointIndex = 1; + + if (numSignificantDigits > maxSignificantDigits) + { + while (CharacterFunctions::isDigit (*s)) + ++s; + break; } } else { - const double maxAccumulatorValue = (double) ((std::numeric_limits::max() - 9) / 10); - if (accumulator [decPointIndex] > maxAccumulatorValue) - { - result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex]) - + accumulator [decPointIndex]; - accumulator [decPointIndex] = 0; - exponentAccumulator [decPointIndex] = 0; - } - - accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit; - exponentAccumulator [decPointIndex]++; - } - } - else if (decPointIndex == 0 && *s == '.') - { - ++s; - decPointIndex = 1; - - if (numSignificantDigits > maxSignificantDigits) - { - while (CharacterFunctions::isDigit (*s)) - ++s; break; } } - else + + result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0]; + + if (decPointIndex != 0) + result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1]; + + if ((*s == 'e' || *s == 'E') && digitsFound) { - break; - } - } + bool negativeExponent = false; - result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0]; + switch (*++s) + { + case '-': negativeExponent = true; // fall-through.. + case '+': ++s; + } - if (decPointIndex != 0) - result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1]; + while (CharacterFunctions::isDigit (*s)) + exponent = (exponent * 10) + (*s++ - '0'); - if ((*s == 'e' || *s == 'E') && digitsFound) - { - bool negativeExponent = false; - - switch (*++s) - { - case '-': negativeExponent = true; // fall-through.. - case '+': ++s; + if (negativeExponent) + exponent = -exponent; } - while (CharacterFunctions::isDigit (*s)) - exponent = (exponent * 10) + (*s++ - '0'); + double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]); + if (decPointIndex != 0) + r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]); - if (negativeExponent) - exponent = -exponent; + return isNegative ? -r : r; } - - double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]); - if (decPointIndex != 0) - r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]); - - return isNegative ? -r : r; } double CharacterFunctions::getDoubleValue (const char* const s) throw() diff --git a/src/text/juce_LocalisedStrings.cpp b/src/text/juce_LocalisedStrings.cpp index 348747a72d..7db328f8c4 100644 --- a/src/text/juce_LocalisedStrings.cpp +++ b/src/text/juce_LocalisedStrings.cpp @@ -51,31 +51,37 @@ const String LocalisedStrings::translate (const String& text) const return translations.getValue (text, text); } -static int findCloseQuote (const String& text, int startPos) +namespace { - juce_wchar lastChar = 0; + CriticalSection currentMappingsLock; + LocalisedStrings* currentMappings = 0; - for (;;) + int findCloseQuote (const String& text, int startPos) { - const juce_wchar c = text [startPos]; + juce_wchar lastChar = 0; - if (c == 0 || (c == '"' && lastChar != '\\')) - break; + for (;;) + { + const juce_wchar c = text [startPos]; - lastChar = c; - ++startPos; + if (c == 0 || (c == '"' && lastChar != '\\')) + break; + + lastChar = c; + ++startPos; + } + + return startPos; } - return startPos; -} - -static const String unescapeString (const String& s) -{ - return s.replace ("\\\"", "\"") - .replace ("\\\'", "\'") - .replace ("\\t", "\t") - .replace ("\\r", "\r") - .replace ("\\n", "\n"); + const String unescapeString (const String& s) + { + return s.replace ("\\\"", "\"") + .replace ("\\\'", "\'") + .replace ("\\t", "\t") + .replace ("\\r", "\r") + .replace ("\\n", "\n"); + } } void LocalisedStrings::loadFromText (const String& fileContents) @@ -123,9 +129,6 @@ void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase) } //============================================================================== -static CriticalSection currentMappingsLock; -static LocalisedStrings* currentMappings = 0; - void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) { const ScopedLock sl (currentMappingsLock); diff --git a/src/text/juce_String.cpp b/src/text/juce_String.cpp index 7047b0c1f4..2d2350eec5 100644 --- a/src/text/juce_String.cpp +++ b/src/text/juce_String.cpp @@ -1029,46 +1029,49 @@ bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const thr } //============================================================================== -static int indexOfMatch (const juce_wchar* const wildcard, - const juce_wchar* const test, - const bool ignoreCase) throw() +namespace WildCardHelpers { - int start = 0; - - while (test [start] != 0) + int indexOfMatch (const juce_wchar* const wildcard, + const juce_wchar* const test, + const bool ignoreCase) throw() { - int i = 0; + int start = 0; - for (;;) + while (test [start] != 0) { - const juce_wchar wc = wildcard [i]; - const juce_wchar c = test [i + start]; + int i = 0; - if (wc == c - || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c)) - || (wc == '?' && c != 0)) + for (;;) { - if (wc == 0) - return start; + const juce_wchar wc = wildcard [i]; + const juce_wchar c = test [i + start]; - ++i; - } - else - { - if (wc == '*' && (wildcard [i + 1] == 0 - || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0)) + if (wc == c + || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c)) + || (wc == '?' && c != 0)) { - return start; - } + if (wc == 0) + return start; - break; + ++i; + } + else + { + if (wc == '*' && (wildcard [i + 1] == 0 + || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0)) + { + return start; + } + + break; + } } + + ++start; } - ++start; + return -1; } - - return -1; } bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw() @@ -1092,7 +1095,7 @@ bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) con else { return wc == '*' && (wildcard [i + 1] == 0 - || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0); + || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0); } } } diff --git a/src/text/juce_StringPool.cpp b/src/text/juce_StringPool.cpp index 2d0a21a61c..4c15b48fc6 100644 --- a/src/text/juce_StringPool.cpp +++ b/src/text/juce_StringPool.cpp @@ -34,46 +34,49 @@ BEGIN_JUCE_NAMESPACE StringPool::StringPool() throw() {} StringPool::~StringPool() {} -template -static const juce_wchar* getPooledStringFromArray (Array& strings, StringType newString) +namespace StringPoolHelpers { - int start = 0; - int end = strings.size(); - - for (;;) + template + const juce_wchar* getPooledStringFromArray (Array& strings, StringType newString) { - if (start >= end) + int start = 0; + int end = strings.size(); + + for (;;) { - jassert (start <= end); - strings.insert (start, newString); - return strings.getReference (start); - } - else - { - const String& startString = strings.getReference (start); - - if (startString == newString) - return startString; - - const int halfway = (start + end) >> 1; - - if (halfway == start) + if (start >= end) { - if (startString.compare (newString) < 0) - ++start; - + jassert (start <= end); strings.insert (start, newString); return strings.getReference (start); } - - const int comp = strings.getReference (halfway).compare (newString); - - if (comp == 0) - return strings.getReference (halfway); - else if (comp < 0) - start = halfway; else - end = halfway; + { + const String& startString = strings.getReference (start); + + if (startString == newString) + return startString; + + const int halfway = (start + end) >> 1; + + if (halfway == start) + { + if (startString.compare (newString) < 0) + ++start; + + strings.insert (start, newString); + return strings.getReference (start); + } + + const int comp = strings.getReference (halfway).compare (newString); + + if (comp == 0) + return strings.getReference (halfway); + else if (comp < 0) + start = halfway; + else + end = halfway; + } } } } @@ -83,7 +86,7 @@ const juce_wchar* StringPool::getPooledString (const String& s) if (s.isEmpty()) return String::empty; - return getPooledStringFromArray (strings, s); + return StringPoolHelpers::getPooledStringFromArray (strings, s); } const juce_wchar* StringPool::getPooledString (const char* const s) @@ -91,7 +94,7 @@ const juce_wchar* StringPool::getPooledString (const char* const s) if (s == 0 || *s == 0) return String::empty; - return getPooledStringFromArray (strings, s); + return StringPoolHelpers::getPooledStringFromArray (strings, s); } const juce_wchar* StringPool::getPooledString (const juce_wchar* const s) @@ -99,7 +102,7 @@ const juce_wchar* StringPool::getPooledString (const juce_wchar* const s) if (s == 0 || *s == 0) return String::empty; - return getPooledStringFromArray (strings, s); + return StringPoolHelpers::getPooledStringFromArray (strings, s); } int StringPool::size() const throw()